【发布时间】:2016-08-17 12:49:00
【问题描述】:
#include <stdio.h>
#include <string.h>
int main() {
char *s[] = {"cricket","tennis","football"};
printf(" String are: \n\n");
printf(" %s \n", *(s));
printf(" %s \n", *(s+1));
printf(" %s \n", *(s+2));
printf(" \n\n");
printf(" Starting locations of the string are: \n\n");
printf(" %d\n",*(s));
printf(" %d\n",*(s+1));
printf(" %d\n",*(s+2));
printf(" \n\n");
return 0;
}
输出:
String are:
cricket
tennis
football
Starting locations of the string are:
134514112
134514120
134514127
s 是一个字符指针数组。 s 具有三个元素,每个元素都存储字符串文字的起始地址。即s[0] 是指向“cricket”起始地址的指针。等等。
我的问题是:
通过观察这些地址,我们可以看到第二个字符串存储在第一个字符串的空字符之后。所有三个字符串都以顺序形式存储。总是这样吗?
【问题讨论】:
-
@Shubham 问题不是关于数组成员的紧凑性,而是关于指针指向的字符串的存储。
-
请注意还有其他字符串文字,例如
" %d\n"和" %s \n"。 -
你为什么还要关心?任何超出数组的访问都是未定义的行为。
-
完全没有保证。另外,编译器可以优化字符串文字的存储方式,如果它检测到您多次使用相同的字符串 - 这通常称为“字符串池”。
标签: c++ c arrays string pointers