将char数组传递给struct成员

Chr*_* P. 4 c struct

我有以下结构:

struct hashItem {
    char userid[8];
    char name[30];
    struct hashItem *next;
};
Run Code Online (Sandbox Code Playgroud)

在下面的函数中,我采用了一个我想分配给结构的char指针(char数组)参数.

void insertItem(struct hashItem *htable[], char *userid, char *name)
{
    int hcode = hashCode(userid);
    struct hashItem *current = htable[hcode];

    struct hashItem *newItem = (struct hashItem*) malloc(sizeof(struct hashItem));
    newItem->userid = userid;
    newItem->name = name;
    [...]
}
Run Code Online (Sandbox Code Playgroud)

相反,我收到以下错误:

hashtable.c: In function ‘insertItem’:
hashtable.c:62: error: incompatible types in assignment
hashtable.c:63: error: incompatible types in assignment
Run Code Online (Sandbox Code Playgroud)

第62行和第63行是`newItem - > ..."行.

Ada*_*ght 7

你几乎肯定不想只将char*分配给char [] - 正如编译器指出的那样,类型是不兼容的,语义不是你想的.我假设您希望struct成员包含两个char*字符串的值 - 在这种情况下,您要调用strncpy.

strncpy(target, source, max_chars);
Run Code Online (Sandbox Code Playgroud)