memcpy后调试器无法正常工作

时间:2014-01-23 18:29:00

标签: c

我写了这段代码:

#include <stdlib.h>

int main(){
    double x;
    foo(&x);
    // ...
}


foo(double *p){
    char bytes[8];
    bytes[0]=62;
    bytes[1]=-120;
    bytes[2]=41;
    bytes[3]=23;
    bytes[4]=-16;
    bytes[5]=-57;
    bytes[6]=47;
    bytes[7]=-40;
    // bytes = 00111110 10001000 00101001 00010111 11110000 11000111 00101111 11011000
    memcpy(p,bytes,sizeof(double));
    // (1)
}

memcpy之后,我希望在x中找到这些位,但是在调试器中的代码行(1)我有

*p = Binary: 1000000000000000000000000000000000000000000000000000000000000000
     Hex: 0x8000000000000000

但是,通过使用fprintf(stderr,"%x",*p);打印值,我得到值1729883e

2 个答案:

答案 0 :(得分:1)

我做了一些mod来让它运行,它实际上填充了x:

#include <stdio.h>
#include <string.h>

bar(){
    double x;
    foo(&x);
    printf("%f\n", x);
}

foo(double *p){
    char bytes[8];
    bytes[0]=-62;
    bytes[1]=-120;
    bytes[2]=41;
    bytes[3]=23;
    bytes[4]=-16;
    bytes[5]=-57;
    bytes[6]=47;
    bytes[7]=-40;
    memcpy(p,bytes,sizeof(double));
}

int main(int argc, char* argv[]){
    bar();
}

输出为:-626117722098128509564427792535309566746344523980579928553066490382037451337019090855228509979567689660741872330473472.000000

如果这对您不起作用,问题可能出在其余代码或调试器设置中。

答案 1 :(得分:0)

尝试

foo(double *p){
  unsigned char * chr;
  bytes[0]=62;
  bytes[1]=-120;
  bytes[2]=41;
  bytes[3]=23;
  bytes[4]=-16;
  bytes[5]=-57;
  bytes[6]=47;
  bytes[7]=-40;
  memcpy(p,bytes,sizeof(double));
  // (1)

  chr = (unsigned char *)p;

  printf("%x", *chr);
}

您获得正确的值62。

相关问题