我正在为我的大学写一个项目。我必须实现此问题中的功能。在此函数中,我必须为结构数组分配内存,并且每次数组填充时,我都必须使用双倍空间重新分配数组。每个结构都有两个成员。第一个成员是char指针,我必须在其中输入字符串。我必须继续这样做,直到用户输入END作为字符串输入为止。之后,我必须释放已分配但未使用的内存。例如,假设我分配了16个结构,而我只使用了10个。我必须释放其余6个结构的内存。除了必须释放内存的那一部分外,我已完成所有这一切。我有一个变量,其中记录了使用的结构数。我的问题在于这个变量。由于某些原因,该变量的值保持不变。我花了几个小时试图找到原因,但我不明白为什么会这样。我也进行了搜索,但没有找到解决我问题的类似方法。这是我的代码。多谢您的协助。struct nameInfo {char *name;char *replacement;};nameInfoT *readNames(int *megethos) {nameInfoT *infos;int i = 0; //metriths pou deixnei se poio struct tou pinaka infos anaferomastechar 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 xrhsimopoiountaireturn infos;} 最佳答案 您应该尝试使代码更具组织性和可读性,并针对不同目的使用明显不同的部分和功能。这一段代码对我来说似乎是错误的: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;,这是正确的,因为重新分配占用了current_size的四倍(您已经加倍了在重新分配之前,然后将其再次乘以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;}关于c - C程序中变量的值不变,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20888479/
10-12 15:57