我尝试给指针的第二个索引赋值,它给了我一个警告
"[Warning] assignment makes integer from pointer without a cast"
它不运行这个程序。我想知道,我在哪里犯了错误?
#include<stdio.h>
void main()
{
char *p="John";
*(p+2)="v";
printf("%s",p);
}
最佳答案
首先,在您的代码中,
char *p="John";
p
指向字符串文字,并尝试修改字符串文字调用 undefined behavior .
相关,C11
,章节 §6.4.5
[...] If the program attempts to modify such an array, the behavior is undefined.
如果你想修改,你需要一个数组,比如
char p[]="John";
其次,*(p+2)="v";
是错误的,因为""
表示一个字符串,而您需要 char
(提示:检查类型 os *(p+2)
)。将其更改为
*(p+2)='v';
要详细说明区别,请引用 C11
,第 6.4.4.4 章,字符常量
An integer character constant is a sequence of one or more multibyte characters enclosed in single-quotes, as in
'x'
.
和章节 §6.4.5,字符串文字
A character string literal is a sequence of zero or more multibyte characters enclosed in double-quotes, as in
"xyz"
.
第三,根据 C 标准,void main()
应该至少 int main(void)
.
关于c - 为指针的索引赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34551014/