c ++ ifstream读取无法存储到短数组缓冲区中

c++ ifstream read can't store into short array buffer

我想将数据从 ifstream 存储到短数组,

但它在打印出来之前就崩溃了 运行 2

short *Data;
// 88200 / (16/8) = 44100

size_t sdata_size = wavHeader.data_size /(wavHeader.bits_per_sample/8);

Data = new short [sdata_size];

std::cout << "run1" << std::endl;

in.read ((char*)&Data,sdata_size);

std::cout << "run2" << std::endl;

好的,正如 Alan Birtles 指出的那样,我做了一些更正,

short *Data;
// 88200 / (16/8) = 44100
Data = new short [wavHeader.data_size/(wavHeader.bits_per_sample/8)];

std::cout << "run1" << std::endl;

in.read ((char*)Data,wavHeader.data_size /(wavHeader.bits_per_sample/8));

std::cout << "run2" << std::endl;

in.close();

// this start point at first element and then increment to next array
short *ptr1 = Data;
// this start at the end element and then decrement to the next,
//- minus 1 for last element
 short *ptr2 = Data 
+(wavHeader.data_size/(wavHeader.bits_per_sample/8)) - 1;

for (; ptr1 < ptr2; ++ptr1, --ptr2)
{
  short tmp = *ptr1;
  *ptr1 = *ptr2;
  *ptr2 = tmp;
}
out.write ((char*)Data,wavHeader.data_size /(wavHeader.bits_per_sample/8));

// clean up the new
delete [] Data;

我想实现的是我想反转wav音频数据并将其写入另一个wav文件。但是输出是错误的,为什么?

预期结果 enter image description here

我的结果

enter image description here

(char*)&Data 应该只是 (char*)Data 并且您应该创建一个大小为 sdata_size / sizeof( short ) 的数组(假设 sdata_size 是 2 的倍数)。