首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

,为什么输出全是0

2012-10-12 
求助,为什么输出全是0?#include stdio.h#include string.h#include stdlib.hchar* GetLenth(int s){

求助,为什么输出全是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]);}} 

热点排行