简体   繁体   English

将值分配给指针char?

[英]assign value to pointer char?

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;

} }

how can i assign a value to *name. 我如何为* name分配一个值。 After i allocated memory for the struct, I allocated memory for the name 在为结构分配内存后,我为名称分配了内存

strncpy((*group_list_ptr)->(*name), "hello", strlen(*group_name));

I am testing it out with "hello", but i want to copy const char *group_name. 我正在用“ hello”进行测试,但是我想复制const char * group_name。

I get errors 我收到错误

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"));

You don't want to dereference the name member, which is the compiler error. 您不想取消引用名称成员,这是编译器错误。

You also can't use sizeof to get the length of a string. 您也不能使用sizeof来获取字符串的长度。 Use strlen(). 使用strlen()。

For strcpy() the last parameter is the length of the string you're copying. 对于strcpy(),最后一个参数是要复制的字符串的长度。 Be sure it's smaller than the destination buffer! 确保它小于目标缓冲区!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM