c - 修改和打印字符串不会产生预期的输出

标签 c pointers

我写了两段代码,我打算有相同的输出,但令人困惑的是,它们有不同的输出。

第一段代码:

#include<stdio.h> 
int main(){
    char a[]="abc";
    char *p=&a;
    char c=++(*p);
    printf("%c,%s\n",c,p);
    return 0; 
}  

输出如下:

b,bbc

第二段代码:

#include<stdio.h>
int main(){
    char *p="abc";
    char c=++(*p); 
    printf("%c,%s\n",c,p);
    return 0; 
}

哪些输出:

a,abc

阻止字符串第一个字符递增的第二段代码发生了什么?

最佳答案

第二个示例尝试更改未定义行为的字符串文字。你通常会因为这样做而崩溃,但在你的情况下,它似乎只是被“忽略”了。

char *p="abc";
char c=++(*p); /* Illegal to change *p. */

标准报价:

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

关于c - 修改和打印字符串不会产生预期的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9979711/

相关文章:

c++ - 这个函数定义是如何工作的?

c - 你如何截断而不是四舍五入? C

c - strtok 改变指针的值

c++ - 如何正确地将指向 blob 的 void 指针转换为结构指针?

c - 从动态数组中删除元素时,是否需要在 memmove 之后重新分配?

c++ - 在调用函数中取消引用指针时出现段错误

c - select(2)为什么叫 "synchronous"多路复用?

c - 为什么 bits/libc-header-start.h 文件夹包含在 stdio.h header 中

c - 10的幂

c++ - 指针声明