我是 C 的新手,所以也许有人可以解释一下为什么我会遇到这个程序的段错误:
#include <stdlib.h>
#include <stdio.h>
int main()
{
char *username = "hello";
char *other;
*other = *username;
return 0;
}
为什么这个段错误?
最佳答案
other
尚未初始化。它指向内存中的某个随机位置,而您要在其中插入一个字符。
您需要为 other
分配一些空间:
char *other = malloc(6); // or 1, or however much space you'll eventually need
*other = *username;
// first char at `other` is now 'h'; the rest is unknown. To make it valid string,
// add a trailing '\0'
other[1] = '\0';
或者如果您正在尝试制作重复的字符串:
char *other = strdup(username);
或者如果你试图让 other
指向与 username
相同的地方:
char *other = username;
关于c中的char指针导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23410427/