C++ Return Char Arrays (not with pointers)
Hello, I would like to return an array of chars from a function so I can read/write to it. I cannot send the original array and edit it as a pointer, because I need to create a new array with some modifications in my program.
Code:
void main() |
Typically to do this you would pass the original and the new string by reference (similar to how strncpy or any of the other string.h functions work).
Here is a quick example I cooked up (using your example). This is hardly "good" code, just threw it together real quick... Code:
#include <stdlib.h> |
Standard C++ explicitly prohibits functions from returning arrays; you'll need to use a pointer or a class which embeds an array. Is the problem that you don't want to use heap memory (i.e. new[])?
ta0kira |
Quote:
OK, here's your basic problem: In your example, you have defined the char array newStr within the main function, and then within your copyArray() function, you define another, local char array with the same name. This is NOT the same char array. The array defined within copyArray() is locally defined, i.e, it exists on the stack, so when copyArray() returns to main, its memory allocation is released, and its contents may be overwritten. To correct this, the array must be defined within main or outside a function, in the common area. Here's one way to do this: Code:
void main() |
Thank you all for your replies. Now that I see what you mention, it makes perfect sense and I am surprised I did not see it before (based on what I know about parameters and pointers).
|
All times are GMT -5. The time now is 04:19 AM. |