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

标签 c pointers multidimensional-array

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

#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中的地址的值。

最佳答案

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

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

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

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

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

关于c - 指向字符数组的指针如何表现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28645575/

相关文章:

c++ - 联盟中的概念问题

c - 我在哪里可以找到编写 C 集合的良好指南?

c - C 中指针的类型转换错误

arrays - 多维数组vbscript中的多个字符串

c - C : Booleans and NOT operator 中的 lambda 演算

c - 如果 proc 存储过程不返回,如何超时

c - 将结构指针数组传递给函数

c++ - 通过函数传递指针然后变得乱码

c++ - 访问二维数组中的元素

javascript - Anuglar2-模型数据跳跃