1

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;
}

1 Answer 1

6

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).

Sign up to request clarification or add additional context in comments.

3 Comments

So when incrementing a pointer it takes into account the type, great! As for the character array, I understand this is a pointer to an array of pointers but why the **.
@CatsLoveJazz, not really. It is an array of pointers (not a pointer to such array). Every element of this array is a pointer to char*, with size of char* size (for example, 8 bytes). Arrays can decay to the pointers (in fact, they do it almost always), so when you say char** cur_name = names names is decayed into pointer to pointer to char.
I will have to digest that, thanks. I was referring to the cur_name variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.