我对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)
这是正确的吗 ?
它需要是:
abc.charptr = malloc(strlen(name)+1); ?
strcpy(abc.charptr, name);
Run Code Online (Sandbox Code Playgroud)
返回值strlen不包括字符串末尾的空零'\ 0'的空格.
你还必须在某个时候释放你分配的内存.
如果您要使用malloc(),则需要记住为空终止符腾出空间.所以malloc(strlen(name)+1)在打电话前使用strcpy().
但是在这种情况下你应该只使用strdup()分配和复制的方式:
abc.charptr = strdup(name);
Run Code Online (Sandbox Code Playgroud)
返回的内存strdup()已经分配,malloc()因此必须通过调用来处理free().