C 中以 NULL 结尾的结构类型数组

2024-04-18

我正在尝试构建一个以 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_tdata,这样我就可以处理它,直到到达 NULL 元素。这可能吗?


对于您的编译器宏NULL似乎被定义为((void *) 0),这是一个指向零的通用指针。自从nist[i](对于任何有效值i) is not一个指向你得到错误的指针。

解决这个问题的最好方法可能是从main通过引用进入函数并使用它,并返回大小。或者通过引用传递一个整数,并将其设置为大小。

还有另一种解决方案,那就是使用指针数组。然后你需要分配每个nist_t单独构造,也将它们全部释放。然后你可以使用NULL来指示数组的末尾。实际上是这样的argv有效,它被终止NULL指针(所以argv[argc]总是等于NULL).

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C 中以 NULL 结尾的结构类型数组 的相关文章

随机推荐