Why doesn't memcpy work when copying a char array into a struct?

左心房为你撑大大i 提交于 2020-01-06 20:00:11

问题


#define buffer 128    

int main(){
  char buf[buffer]="";

  ifstream infile("/home/kevin/Music/test.mp3",ios::binary);
  infile.seekg(-buffer,ios::end);
  if(!infile || !infile.read(buf,buffer)){
      cout<<"fail!"<<endl;
  }
  ID3v1 id3;
  cout<<sizeof(id3)<<endl;
  memcpy(&id3,buf,128);
  cout<<id3.header<<endl;
}


struct ID3v1{
  char header[3];
  char title[30];
  char artist[30];
  char album[30];
  char year[4];
  char comment[28];
  bool zerobyte;
  bool track;
  bool genre;

};

When I do the memcpy, it seems to be pushing too much data into the header field. Do I need to go through each of the structs members and copy the data in? I'm also using c++, but this seems more of a "C" strategy. Is there a better way for c++?


回答1:


As noted in all the comments (you are missing the '\0' character, or when printing C-Strings the operator<< is expecting the sequence of characters to be '\0' terminated).

Try:

std::cout << std::string(id3.header, id3.header+3) << std::endl;

This will print the three characters in the header field.




回答2:


The problem is most likely in that the memcpy does what it does.

It copies the 128bytes into your structure.

Then you try to print out the header. It prints the 1st character, 2nd, 3rd.. and continues to print until it finds the '\0' (string termination character).

Basically, when printing things out, copy the header to another char array and append the termination character (or copy to an c++ string).




回答3:


other problems you may encounter when using memcpy:

  • your struct elements may be align to word boundaries by the compiler. most compilers have some pragma or commandline switch to specify the alignment to use.
  • some cpu's require shorts or longs to be stored on word boundaries, in that case modifying the alignment will not help you, as you will not be able to read from the unaligned addresses.
  • if you copy integers larger than char ( like short, or long ) you have to make sure to correct the byte order depending on your cpu architecture.


来源:https://stackoverflow.com/questions/9649919/why-doesnt-memcpy-work-when-copying-a-char-array-into-a-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!