在我的课堂笔记中对字符串指针迭代感到困惑

Ste*_* Li 4 c

这是我从我的讲义中复制的一大堆代码

/* 2D processing */
printf("\n");
for (i=0; i<3; i++)
    for (j=0; j<3; j++)
        printf("%d ", *(*(ar+i)+j) );
Run Code Online (Sandbox Code Playgroud)

由于ar指针是指地址位置,*(ar+i)实际上是指地址位置的内容ar+i,但我不明白它是如何工作的*(ar+i)+j,它就像内容+数字.

还有一件事是,

(1) char *ptr; ptr = "This is a string";
(2) char *ptr = "This is a string";
Run Code Online (Sandbox Code Playgroud)

为什么(1)不能char *ptr; *ptr="this a string"在声明和作业分开时?

非常感谢你提前.

650*_*502 5

在第一种情况下,ar很可能是指向指针(指定为int **ar;)的指针,因此*(a + i)指针或数组,并且*(*(a + i) + j)是元素.

但是在C和C++中,有一条规则说数组在很多情况下可以隐式地"衰减"到指向第一个元素的指针,因此它也可能ar以其他方式声明:

int **ar;     // (1) A pointer to a pointer
int *ar[3];   // (2) An array of pointers
int ar[3][3]; // (3) An array of arrays
Run Code Online (Sandbox Code Playgroud)

当写入ar + i的情况ar是数组时,它衰减到指向第一个元素的指针(情况2和3),结果是指针的地址(情况2)或数组的地址(3).使用dereference运算符*然后获取指针或数组元素.

当你添加j并且元素是一个数组(例3)时,这个数组在计算加法之前也会衰减到指向它的第一个元素的指针.因此,回顾一下,取决于如何ar定义:

ar                // (1) a pointer to a pointer,
                  // (2) a pointer to array,
                  // (3) an array of array

ar + i            // (1) and (2) address of a pointer
                  // (3) address of array

*(ar + i)         // (1) and (2) a pointer
                  // (3) an array

*(ar + i) + j     // address of an integer in any case

*(*(ar + i) + j)  // an integer in any case
Run Code Online (Sandbox Code Playgroud)

如果这看起来令人困惑,请不要担心,因为它是.通常当你使用*(x + i)是因为x是一个指针然而这就是为什么我猜测它ar已被声明为int **ar;.另请注意,在C和C++ *(x + i)中完全等同于x[i]甚至是i[x].

在第二种情况下,原因是声明是如何用C语写的.

char * s = "foo";
Run Code Online (Sandbox Code Playgroud)

应该读作

(char *s) = ("foo");  // Not legal C, just to show type declaration and
                      // initialization
Run Code Online (Sandbox Code Playgroud)

换句话说,它*是类型声明的一部分s,而不是应用于的操作s.

但请注意

char *s, t;
Run Code Online (Sandbox Code Playgroud)

声明s为a char *ta char.

类型声明可能是C语法中最强大但最困难的部分,因为声明的部分并不明显.例如

int *(*f)(int *(*g)(int x));
Run Code Online (Sandbox Code Playgroud)

是的类型的有效申报f和人名gx是不是不相关的,可以省略.

int *(*f)(int *(*)(int));  // Same as above
Run Code Online (Sandbox Code Playgroud)

f在这种情况下,类型是指向函数的指针,该函数接受指向接受int的函数的指针并返回指向int的指针,并返回指向int的指针.

我的猜测是,绝大多数C程序员需要先思考一下才能解读:-D