分配内存和填充缓冲区的c++函数

ss2ws0br  于 2023-01-15  发布在  其他
关注(0)|答案(1)|浏览(132)

你好,我正在试着读/写我自己的文件格式来学习c++,我已经弄清楚了fstream的阅读部分,但是当我把代码提取到单独的函数中时,我遇到了一些麻烦。
也许是我的期望错了,但我打算这样处理它。

主要功能

int main()
{
  const char* path = "path/to/file.dat";

  // this pointer should be changed to the pointer referencing the heap(?) allocated 
  // buffer inside the function 'readFromFile'
  char* buffer;

  // How can I pass the buffer in a way that sets the pointer to the buffer in
  // this scope to the pointer that is created and allocated inside this function?
  int bufferSize = readFromFile(path, buffer);

  // log colour data to console
  for (int i = 0; i < bufferSize; i += 4)
  {
    std::cout << "rgba(" 
      << buffer[i] << ", "
      << buffer[i + 1] << ", "
      << buffer[i + 2] << ", "
      << buffer[i + 3] << ")" << std::endl;
  }
}

从文件读取函数

// also tried 'char* &buffer'
int readFromFile(const char* path, char* buffer)
}
  // read and parse the file header...
  // this contains the rgba data size

  // allocate data for the buffer based on the header information
  buffer = new char[header.DataLength];

  // fill the buffer with data from the file
  fs.read(buffer, header.DataLength);
  
  // reading is sucessful
  // buffer in this scope is filled

  return header.DataLength;
}

我发现了两种通过引用传递指针的方法:

char* buffer;

readFromFile(x, &buffer);
int readFromFile(x, char** buffer);

readFromFile(x, buffer);
int readFromFile(x, char* &buffer); //is what I ended up going with

我对c++还是个新手,所以内存管理和指针对我来说是相当陌生的概念。我很确定我的问题是一个标准的问题,但是我还没有能够弄清楚如何去做。如果有人能给我指出正确的方向,我将不胜感激。提前感谢。

y4ekin9u

y4ekin9u1#

正如@molbdnilo指出的那样,我最终编写的伪代码是正确的,但在我的实际项目中,我不小心混淆了这两种方法。
旧代码:

char* buffer;

readFromFile(x, &buffer);
int readFromFile(x, char*& buffer);

我的编译器对此做出了回应:initial value of reference to non-const must be an lvalue
检查我的问题中的最后一个代码块,看看哪些代码块最终工作。
感谢大家的快速回复!

相关问题