【发布时间】:2016-12-02 09:01:44
【问题描述】:
#include <stdio.h>
int main()
{
char str[3][15] = {"Pointer to","char","program"};
char (*pt)[15] = str; // statement A
char *p = (char *)str; // statement B
printf("%s\n",p[3]); // statement C - Seg Fault in this line
printf("%s\n",p); // working properly displaying "Pointer to"
printf("%s\n",p+1); // here it is pointing to second element of first array so displaying "ointer to"
printf("%s\n",pt+1); // printing properly "char" as expected
int num[3][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
int (*nm)[3] = num[1];
int *n = num;
printf("n - %d\n",n[10]); // statement D
printf("nm - %d\n",nm[0][0]);
return 0;
}
我的问题:
请帮我弄清楚 char数组和int数组的情况
在上面的程序中,我理解当指针指向 char 数组时 指向 char 的 2D 数组,如语句 A 所示 正常显示,但当它被普通字符指针指向时 并尝试在语句 C 中打印字符,它得到了 SegFault, 相反,它应该打印'n'(第一个数组中的第三个数字字符“指针 to") 所以很困惑为什么如果 int 数组我变得正确 语句 D 中的元素 n = 11 以及为什么在这种情况下(语句 C)它 打印不正确。
如果是 char 数组,数据将如何存储? 如下图所示
char str[3][15] = {{'P','o','i','n','t','e','r',' ','t','o'},
{'c','h','a','r'},
{'p','r','o','g','r','a','m'}};
如果它是这样存储的,那么它应该像语句 D 中显示的整数指针数组一样工作 请帮助我指导这个问题并澄清我在 char 和 int 数组存储的情况下遇到的问题。
【问题讨论】:
-
char str[3][15] = {{'P','o','i','n','t','e','r',' ','t','o','\0'}, {'c','h','a','r', '\0'}, {'p','r','o','g','r','a','m', '\0'}}; -
语句 D 有效,因为
num被分配为编译器使用以下公式访问的单个数组:给定语句num[row][col]那么它与*((int *)num + row * 4 + col)相同。 -
printf("%s\n",p[3]);-->printf("%s\n",&p[3]); -
语句 B 与
p = str[0]相同,因为数组是如何在堆栈上声明的。p[3]返回一个字符,而不是 @LPs 所指出的地址。如果要打印p[3],格式说明符应为%c。
标签: c arrays pointers multidimensional-array char-pointer