我对char数组有一个简单的疑问。我有一个结构:

struct abc {
char *charptr;
int a;
}

void func1()
{
    func2("hello");
}

void func (char *name)
{
    strcpy(abc.charptr, name); >>> This is wrong.
}

由于我没有为charptr分配任何内存,因此该strcpy将导致崩溃。
问题是:对于malloc这个内存,我们可以做吗
abc.charptr = (char *) malloc(strlen(name)); ?
strcpy(abc,charptr, name); >>> Is this (or strncpy) right ?

这是正确的吗 ?

最佳答案

它必须是:

abc.charptr = malloc(strlen(name)+1); ?
strcpy(abc.charptr, name);
strlen的返回值在字符串末尾不包含零零“\ 0”的空间。

您还必须在某个时候释放分配的内存。

关于c - 在C中有char指针时为strcpy,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7730906/

10-12 16:15