[英]unexpected output in c (pointers)
Could someone point out the error in this 有人可以指出这个错误
#include <stdio.h>
void modify (char*s,int x,int y)
{
s[x]=s[y];
}
main()
{
char* s = "random";
modify(s,1,2);
}
The program ends abruptly. 程序突然结束。 I know this may be a very easy question but i am new to c.
我知道这可能是一个非常简单的问题,但我是c的新手。 Thanks !
谢谢 !
It's because it crashes during the assignment in modify
. 这是因为它在分配过程中崩溃
modify
。 The reason for that is that the pointer points to a constant string, one that can not be modified. 这样做的原因是指针指向一个常量字符串,该字符串不能修改。
If you want to modify the string, you can declare it as an array instead: 如果要修改字符串,则可以将其声明为数组:
char s[] = "random";
That's it. 而已。 I once had the same problem.
我曾经遇到过同样的问题。 You should replace this line:
您应该替换此行:
char *s = "random";
With the following one: 与以下之一:
char s[] = "random";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.