2

Why if I increment an array string I get an error while if I pass the value to a function I can make it work? A string array object is not already a pointer to the array elements?

e.g.

void foo(char *a){
    printf("%c", *a);
    a++; // this works
    printf("%c", *a);
}

int main(){
    char a[] = "ciao";
    a++; // I get the error
    foo(a);
    return 1;
}

thanks!

2

3 Answers 3

7

Because arrays are not pointers. They may decay into pointers under certain circumstances (such as passing to a function, as you can see in your code) but, while they remain an array, you cannot increment them.

What you can do it create a pointer from the array such as by changing:

foo(a);

to:

foo(&(a[1]));

which will pass an explicit pointer to the second character instead of an implicit pointer to the first character that happens with foo(a);.

Section 6.3.2.1 of C99 ("Lvalues, arrays, and function designators"), paragraph 3 has the definitive reason why you can't do what you're trying to do:

Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type "array of type" is converted to an expression with type "pointer to type" that points to the initial element of the array object and is not an lvalue.

It's that "not an lvalue" that's stopping you. You cannot change it if it's not an lvalue (so named because they typically appear on the left of assignment statements).

The reason you can do in your first function is because of section 6.7.5.3 ("Function declarators"), paragraph 7:

A declaration of a parameter as "array of type" shall be adjusted to "qualified pointer to type"

In other words, the parameter in the function is an lvalue pointer, which can be changed.

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

Comments

2

The type of your foo's a is a pointer, which you can increment.

The type of your main's a is an array, which you cannot increment.

When you call foo, the address of your array is passed as a new variable of pointer type. You can increment this without the original a being affected.

Comments

1

You can try defining a like this instead:

char* a = "ciao";

3 Comments

then it would be better to deal with strings in c defining a new type: typedef char* string; ??
how exactly would that be better?
I can handle the string also with pointer arithmetic without define another pointer or pass to a function, there is a reason to use char str[] instead of char * str ??

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.