I don’t understand why is the last code block generating 1819043176 1870078063 6581362 0 1 2 3 4 0 6488159… These numbers are not random, but why those numbers? Thank you!
int main(void) {
int x;
int y[10];
int* p;
char* q;
int k;
char* prefix;
k = 0;
while (k < 10) {
y[k] = k;
k = k + 1;
}
x = 42;
printf("address of y are %d %d %d\n", y, y + 1, y + 9);
doit(y + 1);
p = &y[0];
printf("p is %d\n", p);
*p = 42;
p = p + 9;
printf("p is %d\n", p);
*p = 17;
q = "hello world";
p = "hello world";
k = 0;
while (k < 10) {
printf("%d ", q[k]);
k = k + 1;
}
printf("The end\n");
k = 0;
while (k < 10) {
printf("%d ", p[k]);
k = k + 1;
}
printf("The end\n");
}
doit
void doit(int p[9])
{
char* prefix = "";
int k = 0;
printf("p is %d at address %d\n", p, &p);
while (k < 10)
{
printf("%s%d", prefix, *p);
prefix = ", ";
k = k + 1;
p = p + 1;
}
printf("\n");
}
1819043176 is 6C6C6568 in hexadecimal, which is stored as the bytes 68, 65, 6c, 6c on a little-endian machine. These are the first four characters of “hello world”. And so on.
Normally you are not supposed to do these things in C, the results are undefined or implementation-dependent.
If you nevertheless want to peek around in memory then better do it in a more systematical way, for example write a small utility to do a hex dump.