3

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.

babon
  • 3,615
  • 2
  • 20
  • 20
  • 3
    In second case it decay into a pointer and pointers can be incrementated . – ameyCU Sep 05 '15 at 10:40
  • you state you know the root of the problem with the first example. well, then do you understand that the code needs to be prefixed with a `#include ` statement? If you then compile with all warnings enabled the compiler would have told you about 1) warning: unused argc parameter 2) warning: unused argv parameter 3) error: lvalue required as increment operator . If you fix those problems, the code will work just fine. – user3629249 Sep 06 '15 at 17:37

3 Answers3

5

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.

alk
  • 69,737
  • 10
  • 105
  • 255
1

When you pass an array as a function argument, it turns it into a pointer to the first element in the array. This means that when you declare an array and attempt to increment it directly, you are trying to increment an array. When you pass the array as an argument, on the other hand, it is passed as a pointer, so you can increment it.

If you wish to pass the array as an array, and not as a pointer, you might consider using std::array, which is a fixed size container.

EDIT: I apologise. std::array is only available in C++.

1

When you pass array to a function it decays into pointer. Refer here to know about array-decaying

Community
  • 1
  • 1
Karthick
  • 1,010
  • 1
  • 8
  • 24