我有以下代码片段来理解指向特定长度字符数组的指针的工作,以及以下示例代码。
#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+1
和sptr[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+1
和 sptr[1]
具有相同的地址值,但它们的类型不同。 sptr+1
是 char (*)[15]
类型,sptr[1]
是 char *
类型>。
关于c - 指向字符数组的指针如何表现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28645575/