Hello Can somebody explain why second cout in func(char *p) doesn't work:
#include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>开发者_运维知识库
using namespace std;
char *strhex(char *str);
char *func(char *p);
int main()
{
char *ptr;
char *p=strhex("d");
cout<<"main:"<<p<<endl;
cout<<func(p)<<endl;
system("PAUSE");
return 0;
}
char *func(char *p)
{
cout<<"func1:"<<p<<endl;
char buffer[500]="";
char *zbuffer = buffer;
cout<<"func2:"<<p<<endl; ///doesn't work
return zbuffer;
}
char *strhex(char *str)
{
char buffer[500]="";
char *pbuffer = buffer;
int len = strlen( str );
for( int i = 0; i < len ;i++ )
{
itoa(str[i],pbuffer,16);
pbuffer +=2;
};
*pbuffer = '\0';
pbuffer=buffer;
return pbuffer;
}
Edit: i'm using DEV C++ 4.9.9.2 on Windows
One big problem here is that strhex
is returning a pointer to a local variable (buffer[]
). This variable goes out of scope at the end of the function, so the return value points at undefined memory contents that can be overwritten at any time.
Your entire code doesn't work. Both functions return pointers to local arrays, which don't point to anything valid after the function returns. That causes undefined behavior. Since the value of p
is one of these invalid pointers, you can't depend on it to be anything at any particular time — that memory probably gets overwritten during func()
. You need to either new[]
and delete[]
the appropriate memory or, preferably, use a proper C++ data structure like std::string
.
it looks like it is working but the second cout in main is not printing out a value because you are returning an empty buffer.
Adding to others answers:
You need not reset pbuffer
to point to the start of the array and then return it's value:
pbuffer=buffer;
return pbuffer;
you can just say
return buffer;
the array name is also a pointer(pointer to the first element of the array.
精彩评论