【问题标题】:invalid pointer from trying to use realloc for an array of structs in c尝试将 realloc 用于 c 中的结构数组的无效指针
【发布时间】:2013-04-30 16:56:24
【问题描述】:

我的程序可以编译,但我没有正确使用指针和重新分配。我曾尝试查看其他示例,但似乎无法将其转换为我自己的程序。该程序的重​​点是从文件中读取单词并在它们出现多次时增加计数。一旦结构数组超过我的基数(5),我想重新分配空间,复制数组,然后添加下一个单词。

任何帮助将不胜感激!

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BASE 5
#define MAX 50

typedef char *string;

 struct wordCount 
 {
 string word; 
 unsigned int count;
  }; 

 int main (void)
 {  
unsigned int i; 
unsigned int incremented; 
unsigned int j; 
char temp [40];  
struct wordCount wordArray[BASE]; 
struct wordCount *holder;  
FILE *infile;   

j = 0; 
infile = fopen("input.txt","r");
while (fscanf(infile, "%s", temp) == 1) { 
    incremented = 0; 
    for (i = 0; i < j; i++){
        if(strcmp(temp,wordArray[i].word) == 0){
            wordArray[i].count++;
            incremented++; 
        } 
     }
     if (incremented == 0){
        if (j<BASE){     
            wordArray[j].word = (char *)malloc((strlen(temp)+1) * 
                               sizeof(char));
            strcpy(wordArray[j].word,temp); 
            wordArray[j].count = 1; 
            j++;  
        } else {
          holder = realloc(wordArray, sizeof(wordArray) +1);
          *wordArray = *holder;
          wordArray[j].word = (char *)malloc((strlen(temp)+1) * sizeof(char));
          strcpy(wordArray[j].word,temp); 
          wordArray[j].count = 1; 
          j++; 
        }
     }
}

fclose(infile);

/* bring in next file*/
/*delete du plicates */ 
/*sort*/ 

for (i = 0; i < j; i++) {
    printf("%s ", wordArray[i].word);
    printf("%d\n", wordArray[i].count); 
}
/* and when done:*/ 
   for(i = 0; i < j; i++){
      free(wordArray[i].word);
}

return 0; 
 }

【问题讨论】:

    标签: c arrays pointers realloc


    【解决方案1】:

    这是最明显的错误之处:

    holder = realloc(wordArray, sizeof(wordArray) +1);
    

    注意man page of realloc()中的这一行:

    void *realloc(void *ptr, size_t size);
    ...
    除非 ptr 为 NULL,否则它一定是由先前对 malloc()、calloc() 或 realloc() 的调用返回的。

    您的wordArray 是一个静态分配的数组,它不是通过malloc() 或朋友动态分配的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-25
      • 1970-01-01
      • 2021-04-18
      • 1970-01-01
      • 2012-07-29
      • 2013-03-21
      • 2015-07-13
      • 1970-01-01
      相关资源
      最近更新 更多