Realloc example:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LINE_BUF_SZ 1024
static const unsigned int RAY_CHUNK_SIZE = 10;
typedef struct _info
{
char *name;
int num;
char *also;
} info;
void print_data(const info **data, const unsigned int count)
{
unsigned int i = 0;
for ( ; i < count; ++i)
{
printf("Entry %u: %s %d %s\n", i,
data[i]->name, data[i]->num, data[i]->also);
}
}
void free_data(info **data, const unsigned int count)
{
unsigned int i = 0;
for ( ; i < count; ++i)
{
free(data[i]->name);
free(data[i]->also);
free(data[i]);
}
}
int main()
{
char line[LINE_BUF_SZ];
char temp_name_buf[LINE_BUF_SZ], temp_also_buf[LINE_BUF_SZ];
FILE *fp = fopen("dyndata.txt", "r");
if (!fp)
return -1;
unsigned int ray_count = RAY_CHUNK_SIZE;
info **ray = calloc(ray_count, sizeof(*ray));
if (!ray)
return -1;
unsigned int line_count = 0;
while(NULL != (fgets(line, sizeof(line), fp)))
{
if (line_count + 1 == ray_count)
{
// Need realloc
info ** temp = realloc(ray, (ray_count += RAY_CHUNK_SIZE) * sizeof(*ray));
if (!temp)
{
free_data(ray, line_count);
free(ray);
return -1;
}
ray = temp;
}
ray[line_count] = calloc(1, sizeof(info));
if (!ray[line_count])
return -1;
if (3 != sscanf(line,
"%s %d %s",
temp_name_buf,
&ray[line_count]->num,
temp_also_buf))
{
return -1;
}
ray[line_count]->name = strdup(temp_name_buf);
ray[line_count]->also = strdup(temp_also_buf);
++line_count;
}
print_data((const info **)ray, line_count);
free_data(ray, line_count);
free(ray);
fclose(fp);
return 0;
}