首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

初学,指针有关问题

2012-02-17 
初学,指针问题C/C++ code#include iostreamusing namespace std#pragma pack(1)typedef struct yy{//in

初学,指针问题

C/C++ code
#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");}



如上代码为什么指针Z没有返回值?

[解决办法]
传值,你修改的z的副本,不是z本身
至于你申请空间后的操作是想做什么?

C/C++ code
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)形式

热点排行