c中的char指针导致段错误

标签 c segmentation-fault

我是 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/

相关文章:

c - 为什么需要在 C 中的字符串数组中声明字符串的长度?

c++ - 什么会导致在构造子进程期间调用父进程的析构函数?

c - 删除第一个节点时第二次调用出现段错误

C++ rapidxml 不能正确使用保存的 xml_document

c - 段错误: cache lab

c++ - main 之前 C++ 程序中的奇怪段错误

c - 在我的 C 程序中遇到结构和数组问题

c - 调用 Seg Fault 以销毁 malloced 结构

c - 将文件指针移回已读取的字符串

c - 变量前的加法运算符