I'm trying to built a NULL-terminate array of stucts
Here is the code: lzdata.c
#include <stdlib.h>
#include <stdio.h>
#include "nist.h"
int main(int argc,char *argv[])
{
nist_t *nist; /* NIST data */
nist=readnist();
}
The file nist.c
#include <stdlib.h>
#include <stdio.h>
#include "nist.h"
nist_t *readnist()
{
nist_t *nist; /* NIST data */
char line[50];
int len=50;
int i=0;
nist=(nist_t*)malloc(sizeof(nist_t));
while(fgets(line,len,stdin))
{
nist=(nist_t*)realloc(nist,sizeof(nist_t)*(i+1));
sscanf(line,"%s %s %f %lf",nist[i].config,nist[i].term,&(nist[i].j),&(nist[i].level));
++i;
}
nist=(nist_t*)realloc(nist,sizeof(nist_t)*(i+1));
nist[i]=(nist_t)NULL;
return nist;
}
The header file nist.h:
#ifndef NIST_H
#define NIST_H
typedef struct
{
char config[3];
char term[4];
float j;
double level;
} nist_t;
nist_t *readnist();
#endif
The data file, which will be fed to the application via STDIN:
2s ¹S 0.0 0.000000
2p ³P° 1.0 142075.333333
2p ¹P° 0.0 271687.000000
2p ³P 1.0 367448.333333
2p ¹D 0.0 405100.000000
2p ¹S 0.0 499633.000000
3s ³S 0.0 1532450.000000
3s ¹S 0.0 1558080.000000
3p ¹P° 0.0 1593600.000000
3p ³P° 1.0 1597500.000000
3d ³D 1.0 1631176.666667
3d ¹D 0.0 1654580.000000
3s ³P° 1.0 1711763.333333
3s ¹P° 0.0 1743040.000000
3p ³D 1.0 1756970.000000
3p ³S 0.0 1770380.000000
3p ³P 0.5 1779340.000000
3p ¹D 0.0 1795870.000000
3d ³P° 1.0 1816053.333333
3d ¹F° 0.0 1834690.000000
3d ¹P° 0.0 1841560.000000
...
...
When I compile:
$ cc -O2 -o lzdata lzdata.c nist.c
nist.c: In function ‘readnist’:
nist.c:24:2: error: conversion to non-scalar type requested
I've tried changing the line nist[i]=(nist_t)NULL; to nist[i]=(nist_t*)NULL; and I got:
$ cc -O2 -o lzdata lzdata.c nist.c
nist.c: In function ‘readnist’:
nist.c:24:9: error: incompatible types when assigning to type ‘nist_t’ from type ‘struct nist_t *’
I've tried changing the line nist[i]=(nist_t)NULL; to nist[i]=NULL; and I got:
$ cc -O2 -o lzdata lzdata.c nist.c
nist.c: In function ‘readnist’:
nist.c:24:9: error: incompatible types when assigning to type ‘nist_t’ from type ‘void *’
There could be a different number of lines in different data files. I'm seeking to build a NULL-terminated array of nist_t data, so I can process it until I get to the NULL element. Is this possible?
NULLitself is the integer value 0 (though some implementations define it as the pointer value 0). Since you can't mix integers and structures together, what you're trying to do can't work as is. You'd be much better off returning the length of the array by reference.nist_tallocation, before thefgetsloop. Just make surenistisNULL. And don't assign to the same variable you pass intorealloc, think about what would happen in the reallocation would fail, then you loose the original pointer.configandtermstring wont be more than 2 and 3 characters (respectively), since otherwise you will write out of bounds.