问题描述
如果我声明和使用指针是这样的:
If I declare and use a pointer like this:
int counter;
char *pCow = "pCow goes MOO";
for(counter = 0; counter < 14; counter++)
printf("%c", pCow[counter]);
它显示了整个字符串和作品,是的,并没有太多欣喜。
it displays the entire string and works and yeah and there is much rejoicing.
不过,如果我使用的初始化是这样的:
However, if I use an initializer like this:
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]);
程序崩溃和pCow拒绝MOO我享乐主义的快乐!
the program crashes and pCow refuses to moo for my hedonistic pleasure!
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
在精心Eclipse CDT的测试。
Lovingly tested in Eclipse CDT.
推荐答案
在这种情况下, pCow
设置为静态存储器中的C-字符串的地址:
In this case, pCow
is set to the address of a c-string in static memory:
char *pCow = "pCow goes MOO";
在这种情况下, pCow
设置为值'P'
(即 112
)
In this case, pCow
is set to the value 'p'
(i.e., 112
):
char *pCow = {'p','C','o','w',' ','g','o','e','s',' ','M','O','O','\0'};
由于地址 112
最有可能点入禁区/无效的内存,导致你的程序,当您尝试访问炸毁 pCow [计数器]
。
Since the address 112
most likely points into restricted/invalid memory, that causes your program to blow up when you try to access pCow[counter]
.
警告的标量初始化多余的元素的告诉你,这是无视后'P'
所有的东西,因为指针只需要一个值。
The warning "excess elements in scalar initializer" is telling you that it's ignoring all of the stuff after the 'p'
since the pointer only needs one value.
警告的初始化将指针从整数,未作类型转换的告诉你,你正在使用'P'
为指针,这可能不是一个好主意......
The warning "initialization makes pointer from integer without a cast" is telling you that you're using 'p'
as a pointer, which probably isn't a good idea...
您想要做的就是声明 pCow
为字符数组的而不是字符指针的,如果你想使用初始化语法:
What you want to do is declare pCow
as a character array rather than a character pointer if you want to use the initializer syntax:
char pCow[] = {'p','C','o','w',' ','g','o','e','s',' ','M','O','O','\0'};
这篇关于为什么我可以使用指针作为字符串使用双引号声明时,而不是大括号,在C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!