Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regarding array of pointer to char

Tags:

arrays

c

pointers

I understand why this does not work:

int main(int argc, char *argv[]) {
    char *names[] = {"name1", "name2", "name3", "name4"};
    int i = 0;
    while (i++ <= 3) {
        printf("%s\n", *names++);
    }
}

Error:

a.c: In function 'main':
a.c:16: error: wrong type argument to increment
shell returned 1

It's because I am trying to increment an array variable (and NOT a pointer). Please don't mind the line number in the error message, I have lot's of commented code above and below what I have put up here.

However, I do not understand why this piece of code works:

void myfunc(char *names[]) {
    int i = 0;
    while (i++ <= 3) {
        printf("%s\n", *names++);
    }
}


int main(int argc, char *argv[]) {
    char *names[] = {"name1", "name2", "name3", "name4"};
    myfunc(names);
}

How can we increment names in myfunc()? It's still a local array variable in myfunc(). Could someone please help?

Thanks.

like image 965
babon Avatar asked Jul 30 '26 05:07

babon


1 Answers

In the 1st example names is an array. Arrays cannot be incremented.

In the 2nd example names is a pointer. Pointers can be incremented.

Background to why the 2nd example compiles:

A [] in a variable definition in a function declaration is the same as (another) *.

So this

void myfunc(char * names[]);

is equivalent to

void myfunc(char ** names);

The latter makes it obvious that here names is not an array but a pointer.

like image 152
alk Avatar answered Jul 31 '26 18:07

alk