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); }
Moreover, I would recommend reading the chapter βArrays and Pointersβ in FAQ C - start with Question 6.2 and continue reading from there.
source share