Tricolor Tricolor - 3 months ago 8
C Question

Saying a pointer is equal to a position in the memory in C

I have a very simple code here but I can't really understand what's happening on the memory:

#include <stdio.h>
#include <stdlib.h>

int main(){

int v[8], *u = &v[2];
v[2] = 20;
printf("%d",*u);

return 0;
}


So basically, when I ask it to print *u, it will give me 20. I can't understand why. I'm new to pointers and I never saw a example where you're giving a value to a *pointer.

I can only make simple codes like:

#include <stdio.h>
#include <stdlib.h>

int main(){

int a = 10, *b;
b = &a;
printf("%d",*b);

return 0;
}


Which I can easily understand what's happening. Can someone make a comparison on what's happening in the memory on these two cases?

Thank you very much!

Answer
int v[8], *u = &v[2];

This line is defining two things. It's making an array of ints called v that has storage for 8 ints. It's also making a pointer to int, called u that is set to point to the second element in v.

v[2] = 20;

This line sets the second element in the v array to 20. Keep in mind that u also points to this element from the previous line.

printf("%d",*u);

This line just prints the value that u points to. Since it points to the second element in the array v, and that element is set to 20, it'll print 20.

Your second code:

int a = 10, *b;
b = &a;
printf("%d",*b);

Could also be written as:

int a = 10, *b = &a;
printf("%d",*b);

It's just moving the second line onto the first. Then the only difference between your two examples is the array notation.

Comments