C语言 使用strcpy时如何向char指针添加空终止符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28676223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add null terminator to char pointer, when using strcpy
提问by user20842454566
I have a program that's attempting to use the strcpy()function. I know that when one uses a char array such as: char array[10]the null terminator can be set by: array[0] = '\0';However, how would I go about setting the null terminator(s) when using char pointers?
我有一个试图使用该strcpy()函数的程序。我知道当人们使用 char 数组时,例如:char array[10]可以通过以下方式设置空终止符:array[0] = '\0';但是,在使用 char 指针时,我将如何设置空终止符?
EDIT: The program compiles, but gives garbage as output
编辑:程序编译,但输出垃圾
#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;
}
回答by Iharob Al Asimi
You don't need to. Second argument of strcpy()needs to be nulterminated, and the first needs to fit the number of characters in source + the nulterminator.
你不需要。strcpy()需要nul终止的第二个参数,第一个需要适合 source +nul终止符中的字符数。
The problems in your code are:
您的代码中的问题是:
You are using
sizeofoperator in wrong way and you are overwriting thesrcpointer by allocating memory again to it.To get the length of a string you need
strlen()and you don't need to callmalloc()on every pointer.You are getting garbage value because you are copying from uninitialized data since
srcpoints to a newly allocated space, because ofsrc = malloc(sizeof(char));you should not do that.
sizeof(char) == 1by definition, so you are allocating space for just 1 byte, which if it was to be a valid C string, has to be'\0'because there is room for just 1 character.The correct
printf()specifier for a string is"%s", you are using"%c"which is for a character.
您
sizeof以错误的方式使用运算符,并且src通过再次为其分配内存来覆盖指针。要获得您需要的字符串的长度,您不需要
strlen()调用malloc()每个指针。您正在获取垃圾值,因为您从未初始化的数据中复制,因为
src指向新分配的空间,因为src = malloc(sizeof(char));你不应该那样做。
sizeof(char) == 1根据定义,因此您只为 1 个字节分配空间,如果它是有效的 C 字符串,则必须如此,'\0'因为只有 1 个字符的空间。printf()字符串的正确说明符是"%s", 您正在使用"%c"which 用于字符。
The correct way to do it is
正确的做法是
#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;
}
回答by Sourav Ghosh
In your code
在你的代码中
strcpy(target,src);
srcis not null-terminated. This invokes undefined behaviour.
src不是空终止的。这会调用未定义的行为。
Also, by using malloc(sizeof(char));you're allocating memory for ony a single charelement. which is probablyyou don't want.
此外,通过使用malloc(sizeof(char));您为任何单个char元素分配内存。这可能是你不想要的。
Next, as per the man pageof strcpy(), (emphasis mine)
接下来,按照该手册页的strcpy(),(重点煤矿)
The
strcpy()function copies the string pointed to bysrc, including the terminating null byte ('\0')to the buffer pointed to bydest. The strings may not overlap, and the destination stringdestmust be large enough to receive the copy.
该
strcpy()函数将 指向的字符串src(包括终止空字节 ('\0') )复制到 指向的缓冲区中dest。字符串不能重叠,并且目标字符串dest必须足够大以接收副本。
so, as long as
所以,只要
- your source is a proper null-terminated char array (string)
- destination is having enough memory to hold the containts of source
- 您的源是一个正确的以空字符结尾的字符数组(字符串)
- 目的地有足够的内存来保存源的内容
you're good to go. So, you've to
你可以走了。所以,你必须
- null-terminate the
srcarray. - allocate enough memory to
targetso that it can hold the contains ofsrc.
- 空终止
src数组。 - 分配足够的内存,
target以便它可以容纳src.
Lastly, to mention, once you've used a string, you're supposed to use the %sformat specifier with printf()to print the string.
最后,值得一提的是,一旦使用了字符串,就应该使用%s格式说明符 withprintf()来打印字符串。
回答by Coconop
man strcpy
DESCRIPTION
The strcpy() function copies the string pointed to by src, including the terminating null byte ('\0'), to the buffer pointed to by dest.
说明
strcpy() 函数将 src 指向的字符串(包括终止空字节 ('\0'))复制到 dest 指向的缓冲区。
So you don't have to add null-terminate byte if src has it already.
因此,如果 src 已经有空终止字节,则不必添加空终止字节。
BUGS
If the destination string of a strcpy() is not large enough, then anything might happen.
BUGS
如果 strcpy() 的目标字符串不够大,那么任何事情都可能发生。
So :
所以 :
char *src = "Test"; // 4 chars + 'target = malloc(10);
'
target = malloc(sizeof(char)); // Space for 1 char
strcpy(target,src); // Woops !
回答by Gopi
target = malloc((strlen(src) + 1));
Have memory to accommodate the string and a nul terminator. I don't get why you are allocating memory for srcas I see you are using a string literal. Just allocate enough memory for destination and do strcpy()make sure you are not writing to array out of bound.
有内存来容纳字符串和一个 nul 终止符。我不明白你为什么要分配内存,src因为我看到你使用的是字符串文字。只需为目标分配足够的内存,并strcpy()确保您没有越界写入数组。
The right way would be to
正确的方法是
char *src = "Test";
Make a note that when you do
请注意,当您这样做时
char *target = malloc( 10 ) ;
The string "Test"is stored in a read-only location and the address of this location is returned to src. So your string is already in memory and no need to allocate memory for this again which you are trying to do and doing it wrongly. So get rid of malloc()for src
该字符串"Test"存储在只读位置,并且该位置的地址返回到src。因此,您的字符串已经在内存中,无需再次为此分配内存,而您正在尝试这样做并且做错了。所以摆脱malloc()forsrc
回答by Clifford
Answers thus far have addressed the flaws in your code and your apparent misunderstanding rather than your question. Pointers to memory can be indexed just like arrays, so given:
到目前为止,答案已经解决了您的代码中的缺陷和您明显的误解,而不是您的问题。指向内存的指针可以像数组一样被索引,所以给出:
target[0] = '#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;
}
' ;
One can set elements thus:
可以这样设置元素:
##代码##
![C语言 警告:格式 '%d' 需要类型为 'int' 的参数,但参数 2 的类型为 'long int' [-Wformat=]](/res/img/loading.gif)