我正在尝试构建一个以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.cnist.c: In function ‘readnist’:nist.c:24:2: error: conversion to non-scalar type requested
我尝试将行
nist[i]=(nist_t)NULL;
更改为nist[i]=(nist_t*)NULL;
,我得到了:$ cc -O2 -o lzdata lzdata.c nist.cnist.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;
更改为nist[i]=NULL;
,我得到了:$ cc -O2 -o lzdata lzdata.c nist.cnist.c: In function ‘readnist’:nist.c:24:9: error: incompatible types when assigning to type ‘nist_t’ from type ‘void *’
不同数据文件中的行数可能不同。我正在寻求建立一个
nist_t
数据以NULL终止的数组,因此我可以对其进行处理,直到获得NULL元素为止。这可能吗? 最佳答案
对于您的编译器,宏NULL
似乎定义为((void *) 0)
,这是指向零的通用指针。由于nist[i]
(对于i
的任何有效值)不是指针,因此会出现错误。
解决此问题的最佳方法可能是通过引用将main
中的指针传递给函数并使用该函数,然后返回大小。或者通过引用传递一个整数,并将其设置为大小。
还有另一种解决方案,那就是拥有一个指针数组。然后,您需要分别分配每个nist_t
结构,并将它们全部释放。然后,您可以使用NULL
指示数组的结尾。实际上,这是argv
的工作方式,它由NULL
指针终止(因此argv[argc]
始终等于NULL
)。