不明白为什么是段错误

0 c arrays pointers c-strings segmentation-fault

我想很久以前我尝试了以下代码,一切顺利.但现在,我有一个分段错误,我无法找出哪个部分提供它.

#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;
}
Run Code Online (Sandbox Code Playgroud)

这个小代码对我来说似乎是对的,我无法确定是什么问题.

Sad*_*que 5

你没有在这里分配内存:

char *test = NULL; // Empty string
Run Code Online (Sandbox Code Playgroud)

给它一些记忆:

char *test = malloc(sizeof(char) * 50);
Run Code Online (Sandbox Code Playgroud)

循环nul结束后:

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