在C中使用char指针时strcpy

Vin*_*Vin 2 c string char

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

struct abc {
char *charptr;
int a;
}

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

void func (char *name)
{
    strcpy(abc.charptr, name); >>> This is wrong. 
}
Run Code Online (Sandbox Code Playgroud)

这个strcpy会导致崩溃,因为我没有为charptr分配任何内存.问题是:为了记录这个记忆,我们可以做

abc.charptr = (char *) malloc(strlen(name)); ?
strcpy(abc,charptr, name); >>> Is this (or strncpy) right ?
Run Code Online (Sandbox Code Playgroud)

这是正确的吗 ?

shf*_*301 6

它需要是:

abc.charptr = malloc(strlen(name)+1); ?
strcpy(abc.charptr, name);
Run Code Online (Sandbox Code Playgroud)

返回值strlen不包括字符串末尾的空零'\ 0'的空格.

你还必须在某个时候释放你分配的内存.

  • 一般来说,不要转换`malloc`的结果.请参阅http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc. (2认同)

Dav*_*nan 6

如果您要使用malloc(),则需要记住为空终止符腾出空间.所以malloc(strlen(name)+1)在打电话前使用strcpy().

但是在这种情况下你应该只使用strdup()分配和复制的方式:

abc.charptr = strdup(name);
Run Code Online (Sandbox Code Playgroud)

返回的内存strdup()已经分配,malloc()因此必须通过调用来处理free().