为什么如果我递增一个数组字符串会出现错误,而如果我将值传递给一个函数我可以让它工作?字符串数组对象不是指向数组元素的指针吗?
例如
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;
}
谢谢!
最佳答案
因为数组不是指针。在某些情况下它们可能退化为指针(例如传递给一个函数,如您在代码中所见)但是,尽管它们仍然是一个数组,但您不能递增它们。
您可以做的是从数组中创建一个指针,例如通过更改:
foo(a);
到:
foo(&(a[1]));
它将传递一个指向第二个字符的显式指针,而不是传递给 foo(a);
中出现的第一个字符的隐式指针。
C99 的第 6.3.2.1 节(“左值、数组和函数指示符”)第 3 段有明确的理由说明您不能做您想做的事情:
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.
是“不是左值”阻止了你。如果它不是左值(之所以这样命名是因为它们通常出现在赋值语句的左侧),则无法更改它。
您可以在第一个函数中执行的操作是因为第 6.7.5.3 节(“函数声明符”)第 7 段:
A declaration of a parameter as "array of type" shall be adjusted to "qualified pointer to type"
换句话说,函数中的参数是一个左值指针,可以改变。
关于c - c中char数组的指针运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5064443/