struct group {
char *name;
struct user *users;
struct xct *xcts;
struct group *next;
};
int add_group(Group **group_list_ptr, const char *group_name) {
printf("%p\n",group_list_ptr);
*group_list_ptr = malloc(sizeof(struct group));
printf("%p\n",*group_list_ptr);
printf("%p\n",(*group_list_ptr)->name);
(*group_list_ptr)->name = malloc(sizeof(*group_name));
printf("%p\n",(*group_list_ptr)->name);
strncpy((*group_list_ptr)->(*name), "hello", strlen(*group_name));
//printf("%s\n",(*group_list_ptr)->name);
return 0;
}
如何为 *name 赋值。在我为结构分配内存后,我为名称分配了内存
strncpy((*group_list_ptr)->(*name), "hello", strlen(*group_name));
我正在用“hello”测试它,但我想复制 const char *group_name。
我收到错误
lists.c:24:32: error: expected identifier before ‘(’ token
lists.c:24:32: error: too few arguments to function ‘strncpy’
最佳答案
strncpy((*group_list_ptr)->name, "hello", strlen("hello"));
您不想取消引用 name 成员,这是编译器错误。
您也不能使用 sizeof 来获取字符串的长度。使用 strlen()。
对于 strcpy(),最后一个参数是要复制的字符串的长度。确保它小于目标缓冲区!
关于c - 给指针char赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14781493/