用C函数重新分配结构 [英] realloc structure with function in C

查看:71
本文介绍了用C函数重新分配结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的C程序崩溃了,我太新了,无法弄清楚.到目前为止,它非常简单,我认为代码足以找出问题所在.

My C program is crashing and I am too new to figure it out. It's very simple so far and I imagine the code is enough to figure out what is going wrong.

我只是试图逐行读取文件.一旦内存不足,我将使结构的内存增加一倍.如果这还不够,我将提供您所需的其他信息.

I am simply trying to read a file line by line. I will double the memory of a structure once I am out of memory. If this is not enough information, I will give whatever else you need.

非常感谢您的帮助,因为我已经呆了几个小时了.

Thank you very much for any help, as I have been stuck for hours now.

/*
John Maynard
1000916794
7/15/2013
HW-06
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define N 100

struct course
{
   char subject[11];
   int catalogNum;
   int sectionNum;
   int enrollmentTotal;
   int enrollmentCap;
};

void readFile(struct course *d, char* filename);

void double_array_size(struct course *d, int new_size);

int main(void)
{
   char *filename = "hw06-data.csv";
   struct course *d;

   d = malloc( N * sizeof(struct course));

   readFile(d, filename);

}


void readFile(struct course *d, char* filename)
{
   FILE* fp;
   char buffer[100];
   int i = 0, array_size = 100;
   struct course *temp;


   if( ( fp = fopen(filename, "r") ) == NULL)
   {
      printf("Unabale to open %s.\n", filename);
      exit(1);
   }

   fgets(buffer, sizeof(buffer), fp);

   while( fgets(buffer, sizeof(buffer), fp) != NULL)
   {
      if (i == array_size)
      {
         array_size *= 2;
         double_array_size(d, array_size);
         printf("reached limit...increasing array to %d structures\n", array_size);
      }



      i++;
   }
   fclose( fp );
}

void double_array_size(struct course *d, int new_size)
{
   struct course *temp;

   temp = realloc(d, new_size * sizeof(struct course));

   if(temp == NULL)
   {
      printf("unable to reallocate\n");
      exit(1);
   }

   else
      d = temp;
}

推荐答案

realloc()可能返回的指针与原始指针不同,但是您只能将其分配给temp,因此调用函数之后仍可使用原始指针.更改double_array_size()以返回realloc()返回的新指针并调用

realloc() may return a different pointer than the original one but you assign that to temp only so the calling function still works with the original pointer afterwards. Change double_array_size() to return the new pointer returned by realloc() and call

d = double_array_size(d, array_size);

此外,您应该始终检查malloc()realloc()等的结果.如果没有更多可用内存,它们可能会返回NULL

Furthermore you should always check the result fo malloc(), realloc() etc. They may return NULL if there is no more memory available

这篇关于用C函数重新分配结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆