+ -
当前位置:首页 → 问答吧 → 关于C中指针定义的字符串和数组定义的字符串的问题

关于C中指针定义的字符串和数组定义的字符串的问题

时间:2011-12-08

来源:互联网

例:
#include<stdio.h>
int main(void)
{
char string[] ="hello world";
puts(string);
*(string+1) = 'i';
   
puts(string);
return 0;
}
运行这个程序得到的结果是:
hello world
hillo world
其结果是正确的,可是如果"hello world"是以指针的方式定义的:char string[] ="hello world";
程序去不能运行,这是怎么回事?请高手解答

作者: hanxuedog   发布时间: 2011-12-08

当用char *str = "hello world"定义时,字符串"hello world"是常量,不能对它经行更改,对它进行更改是一种无定义的行为。

作者: w1003025426   发布时间: 2011-12-08

#include<stdio.h>
int main(void)
{
char *s ="hello world";
puts(s);
*(s+1) = 'i';

puts(s);
return 0;
}
这个意思??
如果是的话 因为“hello world”字符串常量 是在常量区 不能被修改的~~~与数组是不一样的

作者: zhutou100hao   发布时间: 2011-12-08

还有就是C/C++ code
char str[] = "hello world"char *str = "hello world"
者两种赋值是不同的,第一种是把hello world字符串存放在str数组中,而第二种是str字符指针指向"hello world"这个常量字符串

作者: w1003025426   发布时间: 2011-12-08

char *string = "hello world".

这个字符串存储在只读数据区内. 不可写的. 操作系统会保护而报错.

string 只是保存了他的地址而已.

CSDN 里好多这个问题, 你搜搜看看.

作者: nnrroo   发布时间: 2011-12-08

可是如果"hello world"是以指针的方式定义的:char string[] ="hello world";?
楼主是不是想问
char *string="hello world";
程序不是运行吧
这个问题也快成日经贴了
对某些平台及编译器:字符串常量的地址的内容是不可修改的
char *string="hello world";
string[1]='i'; //出错,常量串所在地址内容不可修改
*(string+1) = 'i'; //同理

作者: keiy   发布时间: 2011-12-08

http://topic.csdn.net/u/20081106/23/02545709-f008-41c5-86d0-d2eb8aa1e162.html?80823

这个里面你看看吧! 

作者: nnrroo   发布时间: 2011-12-08

*(string+1) = 'i';
字符串常量不能修改值吧

作者: quan958201599   发布时间: 2011-12-08

http://blog.csdn.net/mougaidong/article/details/6372765

作者: mougaidong   发布时间: 2011-12-08

引用 3 楼 w1003025426 的回复:

还有就是C/C++ code
char str[] = "hello world" 和 char *str = "hello world"
者两种赋值是不同的,第一种是把hello world字符串存放在str数组中,而第二种是str字符指针指向"hello world"这个常量字符串


那请问char *str[] = "hello,world"; 这种赋值方式和前两种有什么区别?

作者: hanxuedog   发布时间: 2011-12-08

热门下载

更多