我正在尝试构建一个以 NULL 结尾的结构数组
这是代码:lzdata.c
#include <stdlib.h>
#include <stdio.h>
#include "nist.h"
int main(int argc,char *argv[])
{
nist_t *nist; /* NIST data */
nist=readnist();
}
文件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;
}
头文件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
数据文件,将通过 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
...
...
当我编译时:
$ cc -O2 -o lzdata lzdata.c nist.c
nist.c: In function ‘readnist’:
nist.c:24:2: error: conversion to non-scalar type requested
我尝试过改变线路nist[i]=(nist_t)NULL;
to nist[i]=(nist_t*)NULL;
我得到了:
$ 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 *’
我尝试过改变线路nist[i]=(nist_t)NULL;
to nist[i]=NULL;
我得到了:
$ 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 *’
不同的数据文件中可能有不同的行数。我正在寻求构建一个以 NULL 结尾的数组nist_t
data,这样我就可以处理它,直到到达 NULL 元素。这可能吗?