Reputation: 869
I'm trying to understand the below program. Specifically, the definition of cur_name
and the incrementing of the pointer for cur_age
in the printf statement.
*(cur_age + i)
must be indexing each of the integers in the array but I would have expected this to point to successive addresses in memory and not the next integer given ints are 4 bytes? i.e. why not i+4
#include <stdio.h>
int main(int argc, char *argv[])
{
int ages[] = {23, 43, 12, 89};
char *names[] = {"Anne", "Kay", "Joe", "Pete"};
int count = sizeof(ages) / sizeof(int);
int *cur_age = ages;
char **cur_name = names;
for (int i = 0; i < count; i++) {
printf("%s is %d years old.\n", *(cur_name + i), *(cur_age + i));
}
return 0;
}
Upvotes: 1
Views: 184
Reputation: 62613
This is simply how the pointer arithmetics is defined in C. Incrementing the pointer always considered to be incrementation in units, where one unit is the sizeof()
of type being pointed to.
Side note - while int's are commonly 4 bytes in size, this is not set in stone. They might as well be smaller (2 bytes) or longer (really not limit).
Upvotes: 6