如果我声明并使用这样的指针:
int counter;
char *pCow = "pCow goes MOO";
for(counter = 0; counter < 14; counter++)
printf("%c", pCow[counter]);
Run Code Online (Sandbox Code Playgroud)
它显示整个字符串并且工作,是的,并且有很多欢乐.
但是,如果我使用这样的初始化器:
int counter;
char *pCow = {'p','C','o','w',' ','g','o','e','s',' ','M','O','O','\0'};
for(counter = 0; counter < 14; counter++)
printf("%c", pCow[counter]);
Run Code Online (Sandbox Code Playgroud)
程序崩溃了,pCow拒绝为我的享乐主义乐趣而呻吟!
3 Warnings. 0 Errors
line 11 (near initialization for 'pCow') [enabled by default] C/C++ Problem
line 11 excess elements in scalar initializer [enabled by default] C/C++ Problem
line 11 initialization makes pointer from integer without a cast [enabled by default] C/C++ Problem …Run Code Online (Sandbox Code Playgroud) 刚开始使用K&R并点击:
#include <stdio.h>
/* copy input to output; 1st version */
main()
{
int c;
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
}
Run Code Online (Sandbox Code Playgroud)
它只显示我输入的内容,即使它是一串文本.
cacti
cacti
stop repeating what i'm saying
stop repeating what i'm saying
Run Code Online (Sandbox Code Playgroud)
就像那样.
我没有得到的是为什么我不能用一串文本实例化变量c并以相同的方式打印它.(为了示例而忽略while循环)与:
main()
{
int c;
c = "cacti";
putchar(c);
}
Run Code Online (Sandbox Code Playgroud)
其中输出显然只是'd'