我正在编写一个函数,用于存储来自 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;
}
如有任何帮助,我们将不胜感激。
最佳答案
list->data
是指向record
的指针,所以list->data[i]
的类型是record
。您所有的问题行都需要 char *
或至少某种指针,这会导致错误消息。
关于c - 将行存储到动态结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6836626/