I’m very new to dealing with pointers, and my C knowledge is fairly small. I’m trying to understand pointers. I wrote the following code to print a list of variables (a to f) like so:
0
1
2
3
4
5
I wrote the following code to do this:
#include <stdio.h>
int main(){
int a,b,c,d,e,f;
int *p;
int i;
a = b = c = d = f = 0;
p = &a;
for (i = 0; i < 5; i++){
*p += i;
printf("%d\n", *p);
p++;
}
return 0;
}
The idea was it works through the variables and increments each by an ever-increasing number (i). I am assuming that as you initialize the variables at the same time, they’d be placed next to each other in memory. However, I get the following output:
0
1
2
3
-1218283607
If I change the for loop to only go from 0 to 3 (i < 4), it works fine, printer 0 1 2 and 3. But when I wish to print the variable f as well, it doesn’t seem to set it.
As I said, I’m very new to pointers so I’ve probably overlooked something silly, but I’ve been looking through my code over and over, trying to work it out.
Thanks in advance.
There is no guarantee that
a, b, c, d, eandfwill be adjacent in memory. If you want that sort of guarantee you need to use an array.Here
int a[6]is declaring an array namedathat can hold six integers. These six integers can obtained viaa[0],a[1],a[2],a[3],a[4]anda[5]. You are guaranteed thata[0],a[1],a[2],a[3],a[4]anda[5]are layed out contiguously in memory. Thus the linesets
pto the address of the first element. Each increment of this pointer moves us forward one position in the array.The second
forloop shows that first for loops correctly setsa[i]toiforiin{0, 1, 2, 3, 4, 5}. If you run this program you will seeon the console.