Search code examples
arrayscpointersprintfimplicit-conversion

Pointers - unexpected output


I am going through a book and this example isn't explained properly.

As far as I understand, the array variable (nums) is a pointer to an array. Next step I declare a variable choice and give it a value of the address of the array. Then I pass the value behind choice(which I thought would be {1, 2, 3}) to the last element of the array. Printing the last element I get 1. How come that? What don't I understand about pointers?

int nums[] = {1, 2, 3};
int *choice = nums;
nums[2] = *choice;
printf("%i", nums[2]);

Solution

  • nums is not a pointer to an array. nums is an array, and when used in an expression it is converted to a pointer to the first element.

    So when you do this:

    int *choice = nums;
    

    It makes choice point to the first element of nums. Then when you use *choice you get the value of the first element of nums.