2

如何编写包含数组的结构

#include <iostream>
#include <cstdio>

typedef struct {
  int ref; 
  double* ary;
} refAry;

void fillit(double *a,int len){
  for (int i=0;i<len;i++) a[i]=i;
}

int main(){
  refAry a;
  a.ref =10;
  a.ary = new double[10];
  fillit(a.ary,10);
  FILE *of;
  if(NULL==(of=fopen("test.bin","w")))
     perror("Error opening file");
  fwrite(&a,sizeof(refAry),1,of);

  fclose(of);
  return 0;
}

test.bin 的文件大小是 16 字节,我猜是 (4+8) (int + double*)。文件大小应为 4+10*8 (im on 64bit)

~$ cat test.bin |wc -c
16
~$ od -I test.bin 
0000000                   10             29425680
0000020
~$ od -fD test.bin -j4
0000004   0,000000e+00   7,089709e-38   0,000000e+00
                     0       29425680              0
0000020

谢谢

4

4 回答 4

2

您正在将指针(内存地址)写入文件,这不是您想要的。您要写入指针(数组)引用的内存块的内容。这不能通过单次调用 fwrite 来完成。我建议你定义一个新函数:

void write_my_struct(FILE * pf, refAry * x)
{
    fwrite(&x->ref, sizeof(x->ref), 1, pf);
    fwrite(x->ary, sizeof(x->ary[0]), x->ref, pf);
}

你需要一个类似的替代品来代替 fread。

于 2010-02-08T17:56:59.460 回答
1

您的结构实际上并不包含数组,它包含一个指针。如果您真的想要可变长度结构,您需要在其中保留一个 size 字段,以便您知道它有多大。C FAQ有一个示例,说明您正在尝试执行的操作。在您的情况下,它可能看起来像这样:

typedef struct {
    int ref; 
    double ary[1];
} refAry;

#define SIZE_OF_REFARY (sizeof(refAry) - sizeof(double))

分配:

size_t alloc_size = SIZE_OF_REFARY + 10*sizeof(double);
refAry *a = malloc(alloc_size);
a->ref = 10;

来写:

fwrite(a, SIZEP_OF-REFARY + a->ref * sizeof(double), 1, file);
于 2010-02-08T17:54:28.763 回答
0

您的结构包含一个指针,而不是 10 的数组。 sizeof() 选择了它。

你需要像 fwrite(a.ary, sizeof(double), 10, of); 这样的东西。为了写实际的数组

于 2010-02-08T17:59:34.480 回答
0

如果数组的大小始终为 10,则只需将结构更改为:

typedef struct {
  int ref; 
  double ary[10];
} refAry;

然后,您可以使用 sizeof(refAry) 作为大小,通过一次调用 fwrite 将其写出来。

于 2010-02-08T18:02:14.057 回答