op ol
op ol

Reputation: 767

An array of pointer which is converted as pointer to pointer

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?

Upvotes: 1

Views: 38

Answers (2)

rghome
rghome

Reputation: 8841

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.

Upvotes: 3

klutt
klutt

Reputation: 31409

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

Upvotes: 1

Related Questions