我在interview.how中被问到,我们可以改变字符数组和指向字符串的指针的值吗?
这是我的代码片段。
#include<string.h>
int main()
{
char ch[]="abc";
char *ptr="xyz";
ptr="xyz";
//strcpy(ptr,"xyz") is giving segmentation fault
//ch="ABC"; // is throwing error: incompatible types in assignment
strcpy(ch,"ABC");
return 0;
}
有人能解释一下当ptr=“ABC”抛出错误,strcpy(ptr,"xyz")出现分段错误,而strcpy(ch,"ABC")工作正常时,ch=“xyz”是如何工作的吗?
发布于 2014-05-23 18:02:56
在C语言中,您不能直接将字符数组和常量字符串等同起来,因此在
ch = "ABC"
为此,您需要strcpy!
在做的时候
strcpy(ptr, "XYX")
ptr还没有分配任何内存,所以它给出了分段错误!
https://stackoverflow.com/questions/23826251
复制相似问题