Y
Yang Song
HI, I am a little confused about char * and char[].
How would I be able to return a char* created in a function? Is new() the only way? How would I be able to return a
point and a value at the same time? I thought of a possible solution. However, I am not quite sure if I understood
char[] vs. char*. Any insight is greatly appreciated.
Here is the question:
----------------------
....
char * test() {
char[] buf = "abcdef";
return (char *)buf;
}
int main() {
char * p ;
p = test(); // I know that this call is useless. So I tried to modify the test() function to return the
// char * properly. I listed my solution down below. Please feel free to advise.
return 0;
}
----------------------
char * test (char * p) {
p = new char[20];
p = "abcdef";
return p;
}
int main() {
char * p;
char * value;
value = test(p);
cout << value << "\n";
}
This solution returns "abcdef" as the return value. However, p does not pertain the same address that was allocated in
test(). My question is:
1. Is this solution going to cause memory leak because I did not call "delete" to delete the memory allocated?
2. Why was not p's value pertained?
3. How should I change so that I can return a value as well as a char *?
Thanks.
Yang
How would I be able to return a char* created in a function? Is new() the only way? How would I be able to return a
point and a value at the same time? I thought of a possible solution. However, I am not quite sure if I understood
char[] vs. char*. Any insight is greatly appreciated.
Here is the question:
----------------------
....
char * test() {
char[] buf = "abcdef";
return (char *)buf;
}
int main() {
char * p ;
p = test(); // I know that this call is useless. So I tried to modify the test() function to return the
// char * properly. I listed my solution down below. Please feel free to advise.
return 0;
}
----------------------
char * test (char * p) {
p = new char[20];
p = "abcdef";
return p;
}
int main() {
char * p;
char * value;
value = test(p);
cout << value << "\n";
}
This solution returns "abcdef" as the return value. However, p does not pertain the same address that was allocated in
test(). My question is:
1. Is this solution going to cause memory leak because I did not call "delete" to delete the memory allocated?
2. Why was not p's value pertained?
3. How should I change so that I can return a value as well as a char *?
Thanks.
Yang