How does a variable point to a pointer?

Asked

Viewed 193 times

8

Reading this answer on pointers and arrays in C, there is the example below where the variable ptr points to the first element of this array.

int array[42] = {42};
int *ptr = a;

How this pointer identifies the first element of array only by assigning the value a?

  • There’s nothing wrong with your code?

  • I do not know, the code is not mine. I withdrew the answer of the question as I said, but I did not understand the functioning of it.

2 answers

11


Assuming your code is

int array[42] = {42};
int *ptr = array;

compiler will reserve a space for the array. In case he knows that the array will have 42 positions for type int (which is common to have 4 bytes, but depends on platform). This memory area is somewhere in the stack* (which relates to the position of the variable in the function, within the stack frame), has an address for it. So the compiler knows what this location is. He knows what this address is. When an operation requires this address, the compiler knows what to put there.

The second line causes the decay of array for pointer. Then the address where it is array is placed in ptr.

Remember that we are talking about virtual memory. The actual physical address of the memory is calculated while running.


*In other cases it could be in heap, this is implementation detail too, but for all intents and purposes it is so.

8

In the expression below

int *ptr = a;

the "value" of a is converted to a pointer to its first element, internally by the compiler. It is the same as if it had written

int *ptr = &(a[0]); // ponteiro (para o primeiro elemento)

This is the rule defined by Standard C11 paragraph 6.3.2.1p3.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.