我正在寫一個函數,它存儲stdin的行並在結構中動態地爲它分配內存。當我編譯我的代碼時,出現3個錯誤,我不明白爲什麼會出現這些錯誤。將行存儲到動態結構中
的錯誤是如下:
error: incompatible types in assignment
error: incompatible type for argument 1 of `strcpy'
error: incompatible type for argument 1 of `free'
下面是函數:
#define NAMESIZE 20
#define BLOCK 2
typedef struct
{
char last[NAMESIZE];
char first[NAMESIZE];
}name;
typedef struct
{
int id;
name name;
float score;
}record;
typedef struct
{
record *data;
size_t nalloc;
size_t nused;
}record_list;
int list_insert(record_list *list, const record *rec)
{
char * temp;
char lines[512];
size_t i;
list->nalloc = 0;
list->nused = 0;
while(fgets(lines, 512, stdin))
{
if(list->nalloc == list->nused)
{
temp = realloc(list->data, (list->nalloc + BLOCK) * sizeof(char *));
if(temp == 0)
{
fprintf(stderr, "Unable to resize memory\n");
break;
}
list->data = (record *)temp;
list->nalloc += BLOCK;
}
list->data[list->nused] = malloc(strlen(lines) + 1); /*problem line*/
strcpy(list->data[list->nused++], lines);/*problem line*/
}
for(i = 0; i < list->nused; i++)
{
free(list->data[i]); /*problem line*/
}
free(list->data);
return 0;
}
任何幫助將appeciated。
無法真正改變結構。有沒有其他的選擇? – user798774
如果使用當前結構,則不需要爲字符串動態分配內存,而是已經擁有緩衝區(last和first)。然後你只需要做一個realloc(),不需要malloc(),並將該字符串複製到&list-> data [list-> nused ++]。 – Antti