c - 为指针的索引赋值

标签 c pointers variable-assignment

我尝试给指针的第二个索引赋值,它给了我一个警告

"[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/

相关文章:

c - 使用指针从单链表中删除项目

c - 指针和函数

python - 在 jinja 中设置变量

java - 有条件地分配变量以匹配 xslt 模板中的路径

c - 在c中重新加载linux服务

c - c中的 union 初始化

c - 在 C 中的单独函数中初始化指针

c - 第一次使用线程

c - TRIES 实现

javascript - 为什么解构赋值的右侧会忽略其左侧的索引增量