c - c中char数组的指针运算

标签 c pointers math

为什么如果我递增一个数组字符串会出现错误,而如果我将值传递给一个函数我可以让它工作?字符串数组对象不是指向数组元素的指针吗?

例如

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/

相关文章:

javascript - 如何在 javascript 中的圆周上生成随机点

c - 局部静态变量存储在哪里?如果是数据段,为什么它的范围不是整个程序?

c - 如何使用 css 降低 gtk 对话框的标题栏高度?

c - C 中带有指向其他结构数组指针的结构的问题

c++ - 智能指针不能自动用作原始指针?

python - 确定多组整数的交集是否非空的最快方法是什么?

c++ - 宏 ((void(*)())0)() 是什么意思?

c - 在 GBDK c 中使用采样音频播放时如何运行代码?

c - 函数中声明的结构指针

math - 用于游戏开发的三角数学