[英]How to add null terminator to char pointer, when using strcpy
我有一个试图使用strcpy()
函数的程序。 我知道当使用char数组时,例如: char array[10]
,可以通过以下方式设置空终止符: array[0] = '\\0';
但是,在使用char指针时,如何设置空终止符?
编辑:程序编译,但将垃圾作为输出
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char *target;
char *src = "Test";
target = malloc(sizeof(char));
src = malloc(sizeof(char));
strcpy(target,src);
printf("%c\n",target);
return 0;
}
不用了 strcpy()
第二个参数需要以nul
终止,第一个参数需要适合source + nul
终止符中的字符数。
您的代码中的问题是:
您以错误的方式使用sizeof
运算符,并且通过再次为其分配内存来覆盖src
指针。
要获取字符串的长度,您需要strlen()
,而无需在每个指针上调用malloc()
。
由于src
指向新分配的空间,因此您正在从未初始化的数据进行复制,因此您获得了垃圾值,原因是
src = malloc(sizeof(char));
你不应该那样做。
sizeof(char) == 1
按定义),因此您只为1个字节分配空间,如果它是有效的C字符串,则必须为'\\0'
因为只能容纳1个字符。
字符串的正确printf()
说明符是"%s"
,您正在使用用于字符的"%c"
。
正确的方法是
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char *target;
const char *src;
src = "Test"; /* point to a static string literal */
target = malloc(1 + strlen(src)); /* allocate space for the copy of the string */
if (target == NULL) /* check that nothing special happened to prevent tragedy */
return -1;
strcpy(target, src);
printf("%s\n", target);
/* don't forget to free the malloced pointer */
free(target);
return 0;
}
在你的代码中
strcpy(target,src);
src
不是以null结尾的。 这会调用未定义的行为。
另外,通过使用malloc(sizeof(char));
您只为单个char
元素分配内存。 这可能是您不想要的。
接下来,按照strcpy()
的手册页 ,(强调我的)
strcpy()
函数将src
指向的字符串( 包括终止的空字节('\\0'
)strcpy()
复制到dest
指向的缓冲区。 这些字符串可能不会重叠,并且目标字符串dest
必须足够大才能接收副本 。
所以,只要
你很好。 所以,你必须
src
数组。 target
以便可以容纳src
的包含。 最后,要提及的是,一旦使用了字符串,就应该将%s
格式说明符与printf()
以打印字符串。
target = malloc(10);
有内存来容纳字符串和nul终止符。 我不明白为什么要为src
分配内存,因为我看到您正在使用字符串文字。 只需为目标分配足够的内存,并执行strcpy()
来确保您没有写超出范围的数组。
正确的方法是
target = malloc((strlen(src) + 1));
请注意,当您这样做时
char *src = "Test";
字符串"Test"
存储在只读位置,并且该位置的地址返回到src
。 因此,您的字符串已经在内存中,无需为此尝试再次分配并错误地为其分配内存。 所以摆脱src
的malloc()
man strcpy
描述
strcpy()函数将src指向的字符串(包括终止的空字节('\\ 0'))复制到dest指向的缓冲区。
因此,如果src已经有空终止字节,则不必添加它。
臭虫
如果strcpy()的目标字符串不够大,则可能会发生任何事情。
因此:
char *src = "Test"; // 4 chars + '\0'
target = malloc(sizeof(char)); // Space for 1 char
strcpy(target,src); // Woops !
到目前为止,答案已经解决了代码中的缺陷和明显的误解,而不是问题。 可以像数组一样索引指向内存的指针,因此可以这样:
char *target = malloc( 10 ) ;
这样就可以设置元素:
target[0] = '\0' ;
Sourav Ghosh的答案是正确的,但是对于这种特定情况,您应该使用strdup(),因为它可以为您处理内存分配和复制:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
const char *src = "Test"; // You should make this const
char *target = strdup(src); // Duplicate
if (target == NULL) { // Check
return EXIT_FAILURE;
}
printf("%s\n", target);
return EXIT_SUCCESS;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.