读书人

为什么输出全是0

发布时间: 2012-10-12 10:17:04 作者: rapoo

求助,为什么输出全是0?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* GetLenth(int s)
{
char c[4];
char d[4];
memcpy(c, (char *)&s, 4);
for(int i=3,g=0;i>=0,g<4;i--,g++)
{
d[g]=c[i];
}
return d;
}
void main(void)
{

int t=56;
char *g;
g=GetLenth(t);

for(int j=0;j<4;j++)
{
printf("%x\n",g[j]);
}
}

[解决办法]

C/C++ code
#include <stdio.h>#include <string.h>#include <stdlib.h> char* GetLenth(int s){  char c[4]; char*d = (char*)malloc(4);  memcpy(c, (char *)&s, 4);for(int i=3,g=0;i>=0,g<4;i--,g++){d[g]=c[i];}return d;}int main(void) {   int t=56;  char *g;g=GetLenth(t);for(int j=0;j<4;j++){printf("%x\n",g[j]);}free(g);return 1;}
[解决办法]
d数组是在stack上分配的内存,函数结束后,d数组被销毁,返回的指针变成了野指针

C/C++ code
#include <stdio.h>#include <string.h>#include <stdlib.h> void GetLenth(int s, char d[]){  char c[4];    memcpy(c, (char *)&s, 4);for(int i=3,g=0;i>=0,g<4;i--,g++){d[g]=c[i];}}void main(void)  {    int t=56;  char d[4];GetLenth(t, d);for(int j=0;j<4;j++){printf("%x\n",g[j]);}} 

读书人网 >C++

热点推荐