Passing a char array to a structure element

I have the following structure:

struct hashItem { char userid[8]; char name[30]; struct hashItem *next; }; 

In the function below, I take the char (char array) argument that I want to assign to the structure.

 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; [...] } 

Instead, I get the following error:

 hashtable.c: In function 'insertItem': hashtable.c:62: error: incompatible types in assignment hashtable.c:63: error: incompatible types in assignment 

Lines 62 and 63 are the lines `newItem β†’ ...

+4
source share
3 answers

You almost certainly don't want to simply assign char * char [] - as the compiler points out, the types are incompatible, and semantics are not what you think. I assume that you want the members of the structure to contain the values ​​of two char * strings, in which case you want to call strncpy.

 strncpy(target, source, max_chars); 
+7
source

You cannot assign a pointer to a string in an array of characters as you try. Instead, you need to copy the contents of the string using strncpy, as Adam pointed out:

 strncpy (newItem->userid, userid, 8); 

When you declare a structure with an array of characters in it, you allocate memory inside the structure itself to store a string of the specified length.

When you pass a pointer to your function, you pass a memory address (integer) that indicates where to find the line with zero termination.

Assigning a pointer to an array does not make sense. The array has already been allocated memory - it cannot be forced to "point" to another location.

While you can use pointers in your structure, you need to be very careful that when you assign them, you indicate what will work for the entire time that you use in the structure. For example, this code is bad because the string passed to insertItem no longer exists after fillStructure :

 struct hashItem { char * userid; }; void insertItem (struct hashItem * item, char * userid) { item->userid = userid; } void fillStructure (struct hashItem * item) { const char string[] = "testing"; insertItem (item, string); } int main(void) { struct hashItem item; fillStructure (&item); /* item->userid is now a dangling pointer! */ } 

Moreover, I would recommend reading the chapter β€œArrays and Pointers” in FAQ C - start with Question 6.2 and continue reading from there.

0
source

You must change your structure in

 struct hashItem { char userid[8]; char *name; struct hashItem *next; }; 

to assign a char pointer to a name. The structure that you defined char name [30] contains only 30 characters.

0
source