字符串常量VS用C字符数组 [英] String constants vs char arrays in C

查看:187
本文介绍了字符串常量VS用C字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s-in-c\">What是个char []和char * S用C?

更一般性的问题,而不是试图解决的东西,我一直在读的C语言编程的书,他们照顾,使

More of a general question rather than trying to fix something, I've been reading the C programming language book and they take care to make the distinction between

char amessage[] = "blah";
char *pmessage = "blah";

区别在于一个是字符阵列和其他的指针字符串常量。他们说,修改字符数组是可以接受的,但因为它引发未定义的行为不应修改字符串常量。我的问题是:是不是存储在内存中以同样的方式char数组是字符串常量?为什么我可以修改它在

The difference being one is a char array and the other a pointer to a string constant. They say modifying the char array is acceptable but you shouldn't modify string constants as it triggers undefined behavior. My question is: isn't the string constant stored in memory the same way the char array is? Why can I modify it as in

char *p = "this is a string constant";
*(p+2) = 'a';
printf("%s", p);

结束打印全髋关节置换是一个字符串常量正如您所料。我能理解它是如何有意义作为一个字符串的的不应该结束了在运行时被改变,因为它可能会混淆别人/自己的工作在你的code没想到它的价值改变但在纯粹的功能来讲什么是错的,什么是可能触发以及它如何机械可能会适得其反的不确定的行为时,字符数组不会?我只是想知道如果我失去了一些东西有关字符串常量在内存中是如何工作的以及它们是如何被编译器看到的。

Ends up printing "thas is a string constant" as you might expect. I can understand how it would make sense as a string constant shouldn't end up being changed at run time, as it might confuse others/yourself working on your code not expecting it's value to change but in purely functional terms what is wrong with it, what is the undefined behavior that might trigger and how mechanically could it backfire when a char array wouldn't? I'm just wondering if I'm missing something about how string constants work in memory and how they are seen by the compiler.

推荐答案

至少在我的电脑,下面的程序崩溃的:

At least on my computer, the following program crashes:

#include <stdio.h>
int main() { 
  char *p = "this is a string constant";
  *(p+2) = 'a';
  printf("%s", p);
}

如果这似乎是为你工作(这可能会在一定的嵌入式编译器),你刚刚幸运。未定义行为意味着该程序被允许做任何事情。请参见 http://blog.regehr.org/archives/213

If it appears to be working for you (which it might on certain embedded compilers), you're just getting lucky. Undefined behavior means the program is allowed to do anything. See http://blog.regehr.org/archives/213 .

又见<一个href=\"http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s-in-c\">What是个char []和char * S用C?。

这篇关于字符串常量VS用C字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆