|
-
June 30th, 2009, 11:50 AM
#1
Returning char array pointer
Hi!
In an effort to expand my C++ knowledge, I'm writing a little application that generates a random string of lowercase characters, and then returns a pointer that that array. I've got a majority of the app working, it generates the character array fine, but when I try to read the character array outside of the function, I get a bunch of jargon characters.
Here is my code:
Code:
/*
* Create a random string
*/
char* randfname() {
int len = 16; // len of str
srand(time(0)); // to get a true random number
char fname[len]; // char arr that stores file name
char* ptr = fname; // pointer to fname
for(int i = 0; i < len; i++) {
int ascii = (rand() % 25) + 97; // Randomally generate ascii lower case
*(ptr+i) = ascii;
// fname[i] = ascii;
}
for(int i = 0; i < len; i++) { // Test print char arr w/ ptr
cout << *(ptr+i); // Works here
}
return ptr;
}
...
/*
* Test function to ensure that randfname()
* is working.
*/
void testrandfname() {
char* ptr = randfname(); // call randfname
cout << endl;
for(int i = 0; i < 16; i++) {
cout << i << ": " << *(ptr+i) << endl;
}
}
When I print out the array in the randfname() function, it works fine, however, when I pass the pointer to the testrandfname() function and I attempt to print out the array, it doesn't work and I get rubbish data.
I think there is an error where I assign the char* ptr to the pointer returned from randfname() but I'm not sure.
I've tried several different things, but I always arrive at printing rubbish data. Could anybody help me properly read the character array that is returned?
Thanks in advice!
BWiz
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|