How is a variable pointed to a pointer?

3

Reading this answer about 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 does this pointer identify the first element of the array by only assigning the value a ?

    
asked by anonymous 08.10.2015 / 15:41

2 answers

7

Assuming your code is

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

The 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 area of memory is somewhere in the stack 1 (which is relative to the position of the variable in the function, inside the stack frame ), has an address of 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 array to decay for pointer. Then the address where array is placed in ptr .

Remember that we are talking about virtual memory. The actual physical memory address is calculated during execution.

1 In other cases it could be in heap

    
08.10.2015 / 15:55
4

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's the same as if it had written

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

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

    
08.10.2015 / 15:54