C返回带有double的结构

时间:2015-08-11 06:29:20

标签: c

我有某种对象和三种功能。首先从界面接收unix时间戳为8个字节,第二个是getter,第三个用于处理,但我得到0

struct structure{
  double timestamp;
}

struct objstruct{
  struct structure struct_in_obj;
}

typedef struct objstruct *Obj; 

Obj newObj() {
    Obj this = (Obj) malloc(sizeof(struct objstruct));
    bzero(this, sizeof(struct objstruct));
    return this;
}   

void setVal(Obj this, char bytes[8]){
      memcpy(&this->struct_in_obj.timestamp, bytes, sizeof(double)); 
      printf("Value set: %d\n", this->struct_in_obj.timestamp);
    } 

struct structure getter(Obj this){
  printf("Value is still there: %d\n", this->struct_in_obj.timestamp);
  return this->struct_in_obj;
}

int main(){
  Obj obj = newObj();
  setVal(obj, /*8 bytes representing timestamp*/);
  struct structure A;
  A = getter(obj);
  printf("Here value disappears: %d\n", A.timestamp);
}

如果我仅针对此double值制作getter,则可行。复制结构后,为什么我的时间戳为0?有没有办法让它像这样工作,或者最好为double值使用额外的getter?

1 个答案:

答案 0 :(得分:1)

根据代码中的评论,timestamp似乎属于double类型,您尝试使用%d打印该值。那是undefined behaviour