I want to use pointer to store a char array generated by a function, then pass it to another function as a parameter, the code looks like this:
char* randString(){
//generate a rand string formed by 6 letters and numbers
char rSet[36];//a char set contains 0-9 and A-Z
for (int i=0;i<10;i++) rSet[i]=i+48;// get ASCII of 0-9
for (int i=10;i<36;i++) rSet[i]=i+55;// get ASCII of A-Z
char rString[7];
for (int i=0;i<6;i++){
int ind=rand()%36;
rString[i]=rSet[ind];// generate the random string
}
rString[6]='\0';
return rString;
}
void Print(char *b){
cout<<b;
}
int main(int argc, char* argv[])
{
char* a=randString();
Print(a);
}
the randString() function return a string composed by 6 random letter and number, then I store it with *a . when I tracked the pointer with debug, i found the content of *a is correct, with some stuff like "VG5GH2". However, when it was passed to Print() function, the content of the pointer was lost. Even the memory address is still the same, the value in there become some completely random stuff. If I do Print(randString()) also the same thing happend. Could someone help me out about this issue? I am pretty new to C++ and still not very clear with the use of pointer. Many thanks