【发布时间】:2014-05-09 06:51:39
【问题描述】:
我正在尝试构建一个以 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; 更改为 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; 更改为 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 数据数组,所以我可以处理它,直到我到达 NULL 元素。这可能吗?
【问题讨论】:
-
NULL本身是整数值 0(尽管一些实现将其定义为指针值 0)。由于您不能将整数和结构混合在一起,因此您尝试做的事情不能按原样工作。最好通过引用返回数组的长度。 -
在
fgets循环之前,您不需要初始nist_t分配。只要确保nist是NULL。并且不要分配给你传递给realloc的同一个变量,想想重新分配会发生什么会失败,然后你就会失去原来的指针。 -
您的数组包含对象,而不是指向对象的指针,因此您不能将其设置为 null。改为使用指针数组(但您也需要为每个对象分配内存)。或者更好:只需要一个开放数组并存储计数。
-
另外,我希望你的
config和term字符串不会超过 2 个和 3 个字符(分别),否则你会写出界限。 -
未终止的数组和计数变量是大多数语言执行此操作的方式,包括 C++ 的向量对象(它还存储第二个计数以跟踪在需要重新分配之前它可以得到多大)