Hi, I was wondering if someone could help me with an issue I'm having in my code.
#include <stdio.h>
#define SZ 7
int* a[SZ];
int x, y, z;
void populate() {
x = 1;
y = 2;
z = 3;
a[0] = &x;
a[1] = &y;
a[2] = &z;
a[3] = a[0];
a[4] = a[1];
a[5] = a[2];
a[6] = a[3];
}
void printall() {
int i;
printf("x=%1d, y=%1d, z=%1d", x, y, z);
}
void add1each() {
int i;
for( i = 0; i < SZ; i++) {
printf("\na[%1d] = *(%p) = %1d\n", i, a[i], *(a[i]));
a[i] += 1;
printf("a[%d]+1 = %d = 0x%x\n", i, *(a[i]), *(a[i]));
}
}
int main(int argc, char* argv[]) {
populate();
printall();
add1each();
return 0;
}
I expect the output to look something like this:
x=1, y=2, z=3
a[0] = *(0x804a01c) = 1
a[0]+1 = 2 = 0x2
a[1] = *(0x804a03c) = 2
a[1]+1 = 3 = 0x3
a[2] = *(0x804a040) = 3
a[2]+1 = 4 = 0x4
a[3] = *(0x804a01c) = 1
a[3]+1 = 2 = 0x2
a[4] = *(0x804a03c) = 2
a[4]+1 = 3 = 0x3
a[5] = *(0x804a040) = 3
a[5]+1 = 4 = 0x4
a[6] = *(0x804a01c) = 1
a[6]+1 = 2 = 0x2
but it turns out like this:
x=1, y=2, z=3
a[0] = *(0x804a01c) = 1
a[0]+1 = 134520864 = 0x804a020
a[1] = *(0x804a03c) = 2
a[1]+1 = 3 = 0x3
a[2] = *(0x804a040) = 3
a[2]+1 = 0 = 0x0
a[3] = *(0x804a01c) = 1
a[3]+1 = 134520864 = 0x804a020
a[4] = *(0x804a03c) = 2
a[4]+1 = 3 = 0x3
a[5] = *(0x804a040) = 3
a[5]+1 = 0 = 0x0
a[6] = *(0x804a01c) = 1
a[6]+1 = 134520864 = 0x804a020
I see two issues: it seems to cap at 3 (when I'm expecting 4, it returns to 0), and a[0]+1 only gives me the value of the address of a[0] (0x804a020), instead of 2.
Can someone tell me why this is? I've been fiddling with this code for a while now and still don't understand why.
Thanks for your help!