-1

I am now learning the pointer and memory section of C. Now I am stuck on this code. I am not understanding how this code process and how the code shows result contestants[2] = 2. Please consider me as a very new learner and answer briefly how a single code worked and how's the result 2?

#include <stdio.h>

int main()
{
    int contestants[] = {1, 2, 3};
    int *choice = contestants;

    contestants[0] = 2;
    contestants[1] = contestants[2];
    contestants[2] = *choice;
    printf("I'm going to pick contestant number %i\n", contestants[2]); return 0;
}
4

2 回答 2

2
int contestants[] = {1, 2, 3};

contestants is an array of integrs, indexed starting at 0, with values contestants[0] == 1, contestants[1] == 2 and `contestants[2] = 3.

int *choice = contestants;

choice is an integer pointer, assigned here to the address of the contestants array, which is the address of the first element of the contestants array. Therefore, *choice will give you the same result as contestants[0].

contestants[0] = 2;

This assigns 2 to contestants[0]. Now contestants[0] == 2 and, therefore, *choice == 2. The contestants array now looks like {2, 2, 3}.

contestants[1] = contestants[2];

Assigns the value 2 to contestants[1]. Now the contestants array looks like {2, 3, 3}.

contestants[2] = *choice;

Assigns *choice which is still the same as contestants[0] to contestants[2]. So the contestants array looks like {2, 3, 2}.

printf("I'm going to pick contestant number %i\n", contestants[2]); return 0;

Prints contestants[2], which is 2 as you observed.

于 2013-11-09T19:08:28.120 回答
0
  1. contestants is an array of type integers which contains values {1, 2, 3}.
  2. choice is a pointer of type int pointing to valid memory location of contestants.
  3. Each element in array contestants are accessed as contestants[i], where i is index of array starting from 0. contestants[0] = 2; is what assigning value 2 to index location 0.
  4. contestants[2] = *choice; - choice is a pointer, *choice is called dereferencing pointer to get the value pointing by pointer choice which is 2.

Typical memory layout is as follows,

              contestants[] 
choice           0      1     2 
+-----+       +-------------------+
|0x100|------>|  1   |  2   |  3  |              
|     |       |      |      |     |
+-----+       +-------------------+
            0x100  0x104  0x108  
于 2013-11-09T19:04:50.023 回答