将缓冲区写入结构似乎没有起作用

Writing a buffer to a struct seems to not be working

本文关键字:起作用 结构 缓冲区      更新时间:2023-10-16

我正在研究一个旨在为类创建简单版本的项目。当我使用我们定义的" Inode"结构时,我会遇到麻烦。Inode结构定义如下:

struct iNode
 {
  char name[8]; //file name
  int size;     // file size 
  int blockPointers[8]; // direct block pointers
  int used;             // 0 if free; 1 if in use
};

我的项目稍后也有以下代码:

char* inodes = NULL;
inodes = new char[48];
iNode *myinode = new iNode();
int inodemax = 16;
int storedi = 0;
int x = 0;
while(x < inodemax){
  disk.seekg(128 + 48*x,ios::beg);
  disk.read(inodes, 48);
  inodex = (struct iNode *)  &inodes;
  if(inodex -> used == 0){
    inodex -> used = 1;
    for(int i = 0; i < 8; i++){
      inodex -> name[i] = name[i];
    }
    inodex -> size = size;
    storedi = disk.tellg();
    break;
  }
  if(inodex -> used != 0 && x == 15){
    return 4;
  }
  x = x +1;
}

我不太精通C ,因此任何明显的错误都可能以我对语言知识有限(我对C的经验更好)为代价。我的问题是因为我创建了一个测试用例,其中使用的inodes应该为0-但是返回" 4"的返回语句。它不应该达到代码的那一部分。

当我手动更改代码以从Inodes缓冲区获取"二手"字段时,它可以正常工作。因此,我被认为我在将我的char*缓冲区复制到我的结构中做错了什么。

任何人都可以确定我在做什么错以及如何解决它?谢谢,我已经被困了一段时间了。

inodes = new char[48];

inodes是一个指向48个字节的缓冲区的指针。

inodex = (struct iNode *)  &inodes;

这将inodex设置为指向inodes指针。不是inodes指的是指向指针本身。

很明显这应该是:

inodex = (struct iNode *)  inodes;

或更明确:

inodex = reinterpret_cast<struct iNode *>(inodes);