3
#include <stdio.h>

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

int main(void)
{
    char *a[] = {"The first", "The second", "The third"};

    for (int i = 0; i < 3; ++i) {
        printf("%s\n", *a); 
        a++; // error: cannot increment value of type 'char *[3]'
    }

    printa(a); //OK 

    return 0;
}

Thus, my question is why the code a++ in main function causing compile error (error: cannot increment value of type 'char *[3]'). But if I pass array of pointer a to function printa and call a++ on that pointer, it works perfectly.

Thanks,

Banex
  • 2,890
  • 3
  • 28
  • 38
Linh
  • 395
  • 1
  • 3
  • 11

3 Answers3

3

Postfix ++ can't have operand of array type. The type of a in main function is char *[3], i.e. an array of pointers to char while in function printa it is of type char **.

As a function parameter

char *a[]  

is equivalent to

char **a  
haccks
  • 104,019
  • 25
  • 176
  • 264
  • You mean that an array pass to function as a pointer. Thus, `char a[]` is equivalent to `char *a` and `char *a[]` is equivalent to `char **a`. – Linh Aug 17 '15 at 16:47
  • @Linh Yes it is when passed in function. – ameyCU Aug 17 '15 at 16:47
  • Yes. Exactly. When an array is passed to a function then a pointer to its first element is passed to that function. – haccks Aug 17 '15 at 16:48
  • if you speak about function arg then yes, but inside the function *a[] is not the same as a**, no. First is Array and second is pointer – Michi Aug 17 '15 at 16:49
  • Why we cannot `++` on array type? Is it due to `a` is the base of array, thus we can change it? – Linh Aug 17 '15 at 16:53
  • @Linh; Read [this](http://www.c-faq.com/aryptr/arrayassign.html). – haccks Aug 17 '15 at 16:55
  • @haccks: Thanks. I got it :) – Linh Aug 17 '15 at 16:58
1

Simply because array names are non-modifiable l-value. Which cannot be used as left operand in any expression. Therefore, you cannot keep it on the left side of a = expression, or increment it using an increment operator

Haris
  • 12,120
  • 6
  • 43
  • 70
1

When you called printa function, the argument is now another variable of type char **. That variable you can increment.

But inside main, you can not modify a as its the base location of array. Else you get I-Value error.

Austin
  • 1,709
  • 20
  • 40