这是我编写的用于复制字符串常量的程序。
当程序运行时它崩溃了。为什么会这样?
#include <stdio.h>
char *alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char c;
char *l;
main(){
while((c = *alpha++)!='\0')
*l++ = *alpha;
printf("%s\n",l);
}
最佳答案
要在 C 中复制字符串,可以使用 strcpy。这是一个例子:
#include <stdio.h>
#include <string.h>
const char * my_str = "Content";
char * my_copy;
my_copy = malloc(sizeof(char) * (strlen(my_str) + 1));
strcpy(my_copy,my_str);
如果您想避免意外的缓冲区溢出,请使用 strncpy
而不是 strcpy
。例如:
const char * my_str = "Content";
const size_t len_my_str = strlen(my_str) + 1;
char * my_copy = malloc(len_my_str);
strncpy(my_copy, my_str, len_my_str);
关于c - 如何使用指针复制字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18938779/