Home > Enterprise >  Does this code have anything to do with pointers?
Does this code have anything to do with pointers?

Time:01-19

Could somebody help me with this piece of code. I have no idea that what it does.

#include <stdio.h>

int main()
{
    int arr[5],i;
    int a = 1, n = 5;

    for (i=0; i<5;a = arr[i  ]);
    int d = a;
    printf("%d",d);

}

CodePudding user response:

technically this code has pointers. That is because arrays are pointers to the values that are stored in it(arr[0-5]). Every Element of the array points to a Adress anywhere in the memory.

int main()
{
    int arr[10];
    unsigned int x;

    for(x = 0; x < 9; x  )
    {
        arr[x] = x;
        printf("%d ", *(arr x));
    }
    return 0;

}

in this code you can see that you can use an pointer notation to navigate trough an array.

now to your second question. the code that you gave us here is first initializing a array with 5 elements, a int named 'i', a int named 'a' with the value 1, and a int named 'n' that has the value 5.

then you go into a for loop that repeats 5 times. in the for loop you give a the value of the array[i]. but because the array is not filled with numbers it comes a number that is anywhere in the memory.

next you give the variable 'd' the value of 'a'. and at least you print 'd'.

I think that you want it so that you go into a loop and it prints the elements of the array.

int main()
{
    int arr[5], i, a = 1, d;

    for(i = 0; i < 5; i  )
        arr[i] = i;

    for(i = 0; i < 5; i  )
    {
        a = arr[i];
        d = a;
        printf("%d ", d);
    }

    return 1;
}

i think that is what you want.

CodePudding user response:

Of note, we've not put anything of interest into arr, however notice the semicolon on the end of this line:

for (i=0; i<5;a = arr[i  ]);

That's a succinct (confusing?) way of saying

for (i=0; i<5; i  )
{
    a  = arr[i];
}

So a is summing up whatever is in arr.

  •  Tags:  
  • Related