关于double类型和8个字节char型相互转换问题

XD大侠 2013-05-31 03:11:06
头文件
#ifndef cppLib_H
#define cppLib_H
struct Stash{
int size;
int quantity;
int use;
unsigned char* storage;

void initialize(int size);
void cleanup();
int add(const void *element);
void* fetch(int index);
int count();
void inflate(int increase);
};
#endif
cpp文件
#include"cppLib.h"
#include<iostream>
#include<cassert>
#include<ctime>

using namespace std;

const int increment = 100;

void Stash::initialize(int sz){
size = sz;
quantity = 0;
use = 0;
storage = 0;
}

void Stash::cleanup(){
if(storage!=0)
{
cout<<"free storage"<<endl;
delete storage;
storage = 0;
}
}

int Stash::add(const void* element)
{
if(use>=quantity)
inflate(increment);
int startBytes = use*size;
unsigned char* e = (unsigned char*)element;
for(int i=0;i<size;i++)
storage[startBytes+i] = e[i];
use++;
return (use-1);
}

void* Stash::fetch(int index)
{
assert(0<index);
if(index>=use)
return 0;
return &(storage[index*size]);
}

int Stash::count()
{
return use;
}

void Stash::inflate(int increment)
{
assert(increment>0);
int newQuantity = quantity + increment;
int newBytes = newQuantity * size;
int oldBytes = quantity * size;
unsigned char* b = new unsigned char[newBytes];
for(int i=0;i<oldBytes;i++)
b[i] = storage[i];
delete []storage;
storage = b;
//b = 0;
quantity = newQuantity;
}

int main()
{
time_t timer;
srand(time(&timer));
Stash s;
s.initialize(sizeof(double));
s.inflate(increment);
for(int i=0;i<25;i++)
{
double m = (double)(rand()%1000)/3.00;
cout<<m<< " ";
s.add((const char *)&m);
}
char c[8];
cout<<endl;
for(int i=0;i<25;i++)
{
for(int j=0;j<8;j++)
c[j]=s.storage[i+j];
cout<<*(double*)c<< " ";
}
cout<<endl;
system("pause");
}
这个程序的目的是构造一个stash结构体,然后向这个结构体存入25个double型数,然后输出。结果这个程序的第一个输出是对的,后面的输出就是错的。我调试跟踪了一下,好像storage里面的东西也都存入了c【8】里面。但是为什么输出不对。求解。。。。。
...全文
490 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
XD大侠 2013-05-31
  • 打赏
  • 举报
回复
引用 1 楼 zhao4zhong1 的回复:
字节序惹的祸?
我知道错哪里了c[j]=s.storage[i+j];这里要改成c[j]=s.storage[i*8+j];
赵4老师 2013-05-31
  • 打赏
  • 举报
回复
字节序惹的祸?

33,311

社区成员

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

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