C语言 从字符串到字符串的简单strcpy导致整个程序崩溃



抱歉,如果这是一个常见的问题,但我不确定为什么这段代码不会输出任何东西:

#include <stdio.h>
#include <string.h>
int main()
{
char source[] = "hello world!";
char **destination;
strcpy(destination[0], source);
puts(destination[0]);
puts("string copied!");
return 0;
}

看起来它在strcpy()处崩溃了,因为"字符串复制!"也不出现在终端

您的问题是char **destination是指向指针的空指针。destination[0]指向绝对没有。

你可以这样做:

#include <stdio.h>
#include <string.h>
int main()
{
char source[] = "hello world!";
char destination[100];
strcpy(destination, source);
puts(destination);
puts("string copied!");
return 0;
}

或者如果您想动态确定目标的大小:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char source[] = "hello world!";
char *destination = malloc(strlen(source) * sizeof(char)+1); // +1 because of null character
strcpy(destination, source);
puts(destination);
puts("string copied!");

free(destination); // IMPORTANT!!!!
return 0;
}

确保您使用了free(destination),因为它是在堆上分配的,因此必须手动释放。

最新更新