Home › Forums › C Programming › pointers trivia › Reply To: pointers trivia
With this code:
1 2 3 4 5 6 7 8 9 | void function (int recd)<br /> {<br /> printf ("%d", recd);<br /> }<br /> void main()<br /> {<br /> int p=10;<br /> function(p);<br /> } |
The compiler will push the parameter p onto the system stack and jump to the code for the function “function”. Inside the code for “function” a activation record is created which sets up memory for the actual parameters of function and other space for local and temporary variables needed by the compilers code generation algorithms. For intel hardware the code might look something like ( assembly language ):
push p ; push the variable call function
function:
1 2 3 4 5 | push bp ;push the base pointer<br /> mov sp , bp ; save old stack pointer<br /> sub sp , sizeOfData ; set pointer for variables needed<br /> .......<br /> mov [bp] + offset , p ;set value of parameter here |
so that is how the memory might be set up ( look at the assembly output of your compiler if you want to see how any feature is translated ).
For the second example:
1 2 3 4 5 6 7 8 9 10 11 | void function (int *recd)<br /> {<br /> printf ("%d", *recd);<br /> }<br /> void main()<br /> {<br /> int *p;<br /> *p=10;<br /> function ( p );<br /> }<br /> |
memory on the stack is set up for a pointer ( in this case you code should could crash since p is not initialized ) to an int ( 32 bits on a 32 bit system ) and the memory is initialized with the address of p. It is renamed recd and dereferenced to get the value 10. Code should be:
int z;
…
p = & z;
On the third function the pointer parameter is simply initialized with the value of the “p” variable address and then dereferenced. In the last example you have a “pointer-pointer”:
1 2 3 4 5 6 | void main()<br /> {<br /> int **p;<br /> **p = 10; <br /> }<br /> |
You have to intialize these too, like:
1 2 3 4 5 6 7 | <br /> int a;<br /> int * b;<br /> int ** c;<br /> <br /> b = & a;<br /> c = & b; |
so that “c” is a pointer to a pointer ( c holds the address of b ). Now if we dereference “c” once:
1 | *c == the address of a |
and twice :
1 | ** c == the value held in a |
And this is stored on the stack in the same way as the others. I can write some example code and get you some assembly outputs if you need them….