struct nameInfo {
char *name;
char *replacement;
};
nameInfoT *readNames(int *megethos) {
nameInfoT *infos;
int i = 0; //metriths pou deixnei se poio struct tou pinaka infos anaferomaste
char formatstr[15], buffer[SIZE];
int current_size = 0;
int initialized_structs = 1;
nameInfoT *tmp;
sprintf(formatstr,"%%%ds", SIZE -1);
infos = (nameInfoT *)malloc(sizeof(nameInfoT));
if (infos == NULL) {
printf("There was a problem allocating memory\n");
exit(1); //epistrofh se periptwsh pou den mporei na ginei dianomh mnhmhs.
}
for (i = 0; ;i++) {
scanf(formatstr,buffer);
if (strcmp(buffer, "END") == 0) {
break;
}
if ((current_size == initialized_structs) && (initialized_structs != 1)) {
initialized_structs *=2;
tmp = realloc(infos, (sizeof(nameInfoT) * 2 * initialized_structs));
if (tmp == NULL) {
printf("Error allocating Memory");
exit(1);
}
infos = tmp;
initialized_structs *=2;
}
infos[i].name = strdup(buffer);
if (infos[i].name == NULL) {
printf("There was a problem allocating memory\n");
exit(1);
}
current_size++;
}
printf("Initialized structs number is: %d", initialized_structs);
*megethos = current_size; // anathesh sthn timh tou pointer pou tha epistrafei mesw twn parametrwn,
//to plhthos twn structs pou xrhsimopoiountai
return infos;
}
答案 0 :(得分:0)
您应该尝试使您的代码更有条理和可读,并为不同目的使用明显不同的部分和功能。
这段代码对我来说似乎不对:
if ((current_size == initialized_structs) && (initialized_structs != 1)) {
initialized_structs *=2;
tmp = realloc(infos, (sizeof(nameInfoT) * 2 * initialized_structs));
if (tmp == NULL) {
printf("Error allocating Memory");
exit(1);
}
infos = tmp;
initialized_structs *=2;
}
条件(initialized_structs != 1)
不允许执行此代码,因为initialized_structs
是1.此外,您正在调用initialized_structs *=2;
两次,这只是正确的,因为realloc需要 current_size的四倍(你已经在realloc之前加倍initialized_structs
,然后再将它再乘以2)。
它应该是这样的:
if (current_size == initialized_structs) {
initialized_structs *= 2;
tmp = realloc(infos, (sizeof(nameInfoT) * initialized_structs));
if (tmp == NULL) {
printf("Error allocating Memory");
exit(1);
}
infos = tmp;
}
答案 1 :(得分:0)
问题是
&& (initialized_structs != 1)
我不确定你为什么拥有它,但由于initialized_structs
仅在该块内更改并初始化为1
,因此该条件必须始终失败。< / p>
在一个不相关的说明中,你实际上每次都会将分配的内存翻两番。