我有以下結構:傳遞char數組爲結構構件
struct hashItem {
char userid[8];
char name[30];
struct hashItem *next;
};
在功能下面我採取一個字符指針(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;
[...]
}
相反,我得到以下錯誤:
hashtable.c: In function ‘insertItem’:
hashtable.c:62: error: incompatible types in assignment
hashtable.c:63: error: incompatible types in assignment
線62和63是`的newitem - > ...」行
假設我在代碼中的其他位置確定char數組長度小於給定的8/30字節長度,我將如何直接分配它並不複製它? – 2009-09-21 15:38:56
在這種情況下,您會在結構中使用char *,並將指針複製到其中。 char *只是指向某些包含字符的內存的指針。 char []是n個字符的固定長度存儲分配。你不能以合理的方式在它們之間進行分配。 – 2009-09-21 15:43:03
@Christian:確定長度與您是否分配或複製無關。你不能分配給C中的數組。該語言不允許。您必須決定是否希望新的hashItem包含傳遞給insertItem的字符串副本(在這種情況下,使用某種副本以及某種邊界檢查)或指向它的指針(在這種情況下,使用char *而不是結構中的char [])。 – 2009-09-21 15:55:45