C 中具有 char 指针时的 strcpy
我对 char 数组有一个简单的疑问。我有一个结构:
struct abc {
char *charptr;
int a;
}
void func1()
{
func2("hello");
}
void func (char *name)
{
strcpy(abc.charptr, name); // This is wrong.
}
这个 strcpy
将导致崩溃,因为我没有为 charptr
分配任何内存。 问题是:对于malloc
这块内存,我们可以
abc.charptr = (char *) malloc(strlen(name)); //?
strcpy(abc.charptr, name); // Is this (or strncpy) right ?
这样做吗?
I have a simple doubt in char
arrays. I have a structure:
struct abc {
char *charptr;
int a;
}
void func1()
{
func2("hello");
}
void func (char *name)
{
strcpy(abc.charptr, name); // This is wrong.
}
This strcpy
will result in a crash since I do not have any memory allocated to the charptr
.
The question is : For malloc
ing this memory, can we do
abc.charptr = (char *) malloc(strlen(name)); //?
strcpy(abc.charptr, name); // Is this (or strncpy) right ?
Is this right ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您要使用
malloc()
,您需要记住为空终止符腾出空间。因此,在调用strcpy()
之前使用malloc(strlen(name)+1)
。但在这种情况下,您应该只使用
strdup()
一次性完成分配和复制:strdup()
返回的内存已使用malloc 分配()
,因此必须通过调用free()
来释放。If you were to use
malloc()
you need to remember to make room for the null-terminator. So usemalloc(strlen(name)+1)
before callingstrcpy()
.But in this case you should just use
strdup()
which does the allocation and copying in one go:The memory returned by
strdup()
has been allocated withmalloc()
and hence must be disposed of with a call tofree()
.它需要是:
strlen
的返回值不包含字符串末尾的空零“\0”的空间。您还必须在某个时候释放分配的内存。
It needs to be:
The return value of
strlen
doesn't include space for the null zero '\0' at the end of the string.You will also have to free your allocated memory at some point.
请注意 +1,因为您需要为空终止符留出空间。那么strcpy()就可以了。
Note the +1, since you need space for the null terminator. Then strcpy() will be fine.