我用这个代码,通过这种结构,即时通讯设法使功能来添加项目到这个结构realloc()的无效NXT大小
typedef struct goods{
char *name;
int num;
} goods;
void addWord(char *what, goods *where, int pnr, int *arrsize, int n){
if (pnr >= *arrsize){
where = (goods*)realloc(where,*arrsize*2*sizeof(goods*));
*arrsize*=2;
}
where[pnr].name = (char*)malloc(strlen(what)*sizeof(char));
strcpy(where[pnr].name,what);
where[pnr].num = n;
}
在主要功能的阵列我有这个:
int extstore = 1;
goods *store = (goods*)malloc(1*sizeof(goods*));
addWord(line, store, nr, &extstore, n);
为什么我在addWord()
的行where = (goods*)realloc(where,*arrsize*2*sizeof(goods*));
上得到“无效的下一个大小”运行时错误?
编辑:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct goods{
char *name;
int r;
} goods;
int main()
{
int linelen, i, nr = 0, current_r;
char *line = NULL;
size_t len = 0;
int extstore = 1;
goods *store;
store = malloc(extstore*sizeof(goods*));
while (1){
while ((linelen = getline(&line, &len, stdin)) != -1){
if (line[linelen - 1] == '\n'){
line[linelen - 1] = '\0';
}
linelen = strlen(line);
if (line[0] == '#'){
if (sscanf(line,"#%d",¤t_r) != 1){
printf("bad input.");
return 0;
} else continue;
}
if (nr >= extstore){
store = realloc(store,extstore * sizeof(goods*) * 2);
extstore*=2;
}
store[nr].name = malloc(strlen(line)*sizeof(char));
strcpy(store[nr].name,line);
store[nr].r = current_r;
nr++;
}
if (linelen == -1) break;
}
printf("\n");
for (i = 0;i < nr;i++){
printf("%s, [id:%d]\n", store[i].name, store[i].r);
}
return 0;
}
你忘了问一个问题。 – Mureinik 2014-12-06 16:02:44
@Mureinik:他问了一个问题。这是“为什么我的代码中出现错误,在指定的行?”。诚然,对问号没有明确的问题是一个坏主意。至少他提供了所有的信息来弄清楚什么是错的... – Deduplicator 2014-12-06 16:10:46
你得到了什么样的错误? – 4pie0 2014-12-06 16:14:11