c - 不明白为什么会出现段错误

标签 c arrays pointers segmentation-fault c-strings

我想前段时间我尝试了以下代码并且一切顺利。 但是现在,我有一个段错误,我无法找出它是由哪个部分提供的。

#include <stdio.h>
#include <stdlib.h>

int main() {
    char *test = NULL; // Empty string
    char *a = "programming test";
    int i = 0;

    /* While the string "a" does not encounter a space,
       I put its characters in the empty string "test" one by one. */

    while(a[i] != ' ') {
        test[i] = a[i];
        i++;
    }

    printf("%s\n", test);

    return 0;
}

这个小代码对我来说似乎是正确的,我无法确定哪里出了问题。

最佳答案

你没有在这里分配内存:

char *test = NULL; // Empty string

给它一些内存:

char *test = malloc(sizeof(char) * 50);

在循环 nul 之后终止它:

while(a[i] != ' ') {
    test[i] = a[i];
    i++;
}
test[i] = '\0';
printf("%s\n", test);

关于c - 不明白为什么会出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29207936/

相关文章:

在C中复制字符

c - rand()/RAND_MAX 是否返回 [0, 1) 或 [0,1]?

java - 创建一个函数来检查数组中的任何索引是否具有相同的值

python - 不同大小数组的 Numpy 运算

c - 使用指针来计算 _ 和 !在 C 的 main 函数之外的字符串中

c - 这个数组在每种情况下都在做什么?

C 加上 int 和 float,类型变了

javascript - JavaScript 数组是如何实现的?

c - 未初始化和空指针之间的区别

c - 尝试访问 sbrk 可用空间的梯子部分后出现段错误