c - 如何使用指针复制字符串

标签 c string pointers

这是我编写的用于复制字符串常量的程序。

当程序运行时它崩溃了。为什么会这样?

#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/

相关文章:

c - 使用宏初始化结构

c# - 我在这里用什么代替 int ? C#命令

C++调用函数

c++ - C++:在程序中创建一个指针,然后在另一个程序中访问该位置

c - 使用 fgets 和 strtok 读取 C 中的文件?

c - 使用具有 MFCC 功能的 kohonen 网络进行语音识别。如何设置神经元及其权重之间的距离?

c - 我是否误解了这个关于字符串文字范围的例子?

c - 用C读取txt文件

string - Swift 文本文件到字符串数组

C# 声明一个跨越多行的字符串