C ++ ifstream读取不能存储到短数组缓冲区

时间:2018-11-12 07:37:03

标签: c++ arrays pointers ifstream

我想将数据从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

1 个答案:

答案 0 :(得分:3)

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