1

In this source code,

#include <stdio.h>

void test(char *a[]);

int main(void)
{
        char *k[] = {"123", "4567", "89101112"};

        test(k);
}

void test(char *a[])
{
        ++a;
        ++a[0];
        a[1] += 4;

        printf("%s\n", a[-1]);
        printf("%s\n", a[0]);
        printf("%s\n", a[1]);
}

Output

123
567
1112

I understand ++a; but ++a[0] and a[1] += 4; seems awkward. The single object a remembers three properties and the result is printed as above. What is the reason for this?

2
  • What result did you expect? Commented Apr 2, 2021 at 8:06
  • @klutt I expected the same result as shown, but I've never seen an explanation about this. I thought I had to declare two additional variables to do ++a[0]; and a[1] += 4;. Commented Apr 2, 2021 at 8:11

2 Answers 2

3

The parameter a is a pointer to the array k which is an array of pointers to characters (char*). Each pointer is initialised to point to the start of the strings.

So:

a = k = &k[0]

a[0] = "123"
a[1] = "4567"
a[2] = "89101112"

Here is what happens:

a++

The pointer a is advanced one position, so a now points to k[1].

++a[0]

We take the pointer at a[0] (which is k[1]) and advance it one position. So k[1] now points to the "5" and not "4".

a[1] += 4

We take the pointer at a[1] (which is k[2]) and advance it four positions. So k[2] now points to the second "1".

printf("%s\n", a[-1]);
printf("%s\n", a[0]);
printf("%s\n", a[1]);

Since we advanced a, then a[-1] points to k[0], a[0] to k[1], a[1] to k[2]. We print out the new values of the k array modified as described above.

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

1 Comment

Did you mean == instead of ++
1

In addition to rghomes answer, I'd like to add a version with additional printouts that shows pretty clear what's going on.

void test(char *a[])
{
        // Before advancing the pointer, we cannot print a[-1] 
        // printf("%s\n", a[-1]);
        printf("%s\n", a[0]);
        printf("%s\n\n", a[1]);

        ++a;

        printf("%s\n", a[-1]);
        printf("%s\n", a[0]);
        printf("%s\n\n", a[1]);

    
        ++a[0];

        printf("%s\n", a[-1]);
        printf("%s\n", a[0]);
        printf("%s\n\n", a[1]);

        a[1] += 4;

        printf("%s\n", a[-1]);
        printf("%s\n", a[0]);
        printf("%s\n", a[1]);
}

Output:

$ ./a.out
123
4567

123
4567
89101112

123
567
89101112

123
567
1112

Comments

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.