初学,指针问题

mqmmx 2007-11-29 09:29:04

#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没有返回值?
...全文
67 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
mqmmx 2007-11-29
  • 打赏
  • 举报
回复
多谢“吃话梅的超人”我把代码按你说的改了下,能行了,但现在有两种方法,不是哪种好些


#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* Z = (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");
}

mmidd 2007-11-29
  • 打赏
  • 举报
回复
学习一下,好像是应该用二级指针做参数
mqmmx 2007-11-29
  • 打赏
  • 举报
回复
其实我只想要struct的BYTE数组型式返回用方法来实现,就像如下这句的结果就行了
BYTE* Z = (BYTE*)(&x);
chmdcr 2007-11-29
  • 打赏
  • 举报
回复
函数修改为
void getbytes(const STRUCT *v, BYTE **bt)形式
chmdcr 2007-11-29
  • 打赏
  • 举报
回复
如果想修改一级指针 请用二级指针做参数
谢谢
ckt 2007-11-29
  • 打赏
  • 举报
回复
传值,你修改的z的副本,不是z本身
至于你申请空间后的操作是想做什么?


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);

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧