初学,指针问题
#include <iostream>using namespace std;#pragma pack(1)typedef struct yy{// int a; char b; short c; };typedef unsigned char BYTE;template<typename STRUCT>void getbytes(const STRUCT *v, BYTE *bt){ size_t size = sizeof(*v); //bt = (BYTE *)v; if ( bt == NULL) { printf("%d\n",size); bt = (BYTE *)malloc(sizeof(BYTE)* size); //return; if ( bt == NULL) { printf("not enough memory "); return; } } memcpy(bt, (BYTE *)v, size); for (int i=0; i < size; i++) { printf("%d\n",bt[i]); printf("%d\n",&bt[i]); }}int main(){ yy x; //x.a = 1; x.b = 2; x.c = 3; //BYTE* bt = (BYTE*)(&x); BYTE *Z = 0; //BYTE b[sizeof(x)] = {0}; getbytes(&x, Z); if ( Z == NULL) { printf("Null"); system("pause"); return 0; } for (int i=0; i < sizeof(x); i++) { //cout<<(int)b[i]<<endl; printf("%d\n",Z[i]); printf("%d\n",&Z[i]); } system("pause");}void getbytes(const STRUCT *v, BYTE** bt){ size_t size = sizeof(*v); if ( *bt == NULL) { printf("%d\n", size); *bt = (BYTE *)malloc(sizeof(BYTE)* size); //return; if ( *bt == NULL) { printf("not enough memory "); return; } }}getbytes(&x, &Z);
[解决办法]
函数修改为
void getbytes(const STRUCT *v, BYTE **bt)形式