指向字符数组的指针如何表现?

How pointer to array of character behaves?

我有以下代码片段来理解指向特定长度字符数组的指针的工作,以及以下示例代码。

#include <stdio.h>
int main(){

    char sports[5][15] = {

            "cricket",
            "football",
            "hockey",
            "basketball"
    };

    char (*sptr)[15] = sports;

    if ( sptr+1 == sptr[1]){

        printf("oh no! what is this");
    }

    return 0;
}

sptr+1sptr[1]怎么能相等呢?因为第一个意思是把sptr中存的地址加一,第二个意思是得到存储在 sptr + 1.

中的地址的值

虽然解引用指针编译器会这样做,

a[i] ==  *(a+i);

您可以使用 printf 语句验证这一点。

printf("%p\n",sptr[1]);
printf("%p\n",sptr+1);

参考这个link.

sptr 是指向 15 char 数组的指针。用 sports 初始化后,sptr 指向 sports 数组的第一个元素,即 "cricket"

sptr + 1 是指向 sports 的第二个元素的指针,即 "football"sptr[1] 等同于 *(sptr + 1) ,它是指向 [ 的第一个元素的指针=20=],即

sptr + 1 ==> &sports[1] 
sptr[1]  ==> &sports[1][0]   

由于 pointer to an array and pointer to its first element are both equal in valuesptr+1 == sptr[1] 给出 true 值。

请注意,虽然sptr+1sptr[1]具有相同的地址值,但它们的类型不同。 sptr+1char (*)[15] 类型,sptr[1]char * 类型。