如何使用指针复制字符串 [英] How to copy a string using a pointer
本文介绍了如何使用指针复制字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我编写的用于复制字符串常量的程序.
Here's a program I wrote to copy a string constant.
程序运行时崩溃.为什么会这样?
When the program is run it crashes. Why is this happening ?
#include <stdio.h>
char *alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char c;
char *l;
main(){
while((c = *alpha++)!='\0')
*l++ = *alpha;
printf("%s\n",l);
}
推荐答案
要在C语言中复制字符串,可以使用strcpy.这是一个示例:
To copy strings in C, you can use strcpy. Here is an example:
#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
.例如:
If you want to avoid accidental buffer overflows, use strncpy
instead of strcpy
. For example:
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);
这篇关于如何使用指针复制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文