Returning a dynamically allocated array from a function

This a very simple program I created because I dont understand how do this. My goal is to be able to use the pointer *s5 throughout the program. For example I would to like to call other functions and pass that pointer through the function. I understand the dynamic allocation and pointers for the most part but Im confused here because the "new char[20]" variable will die after the function and I dont want it to.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36


#include <iostream>
#include <cstdlib>
#include <cstring>

using namespace std;

void testArray ( char *s5 );

int main ( int argc, char *argv[] )
{
	char *s5 = 0;

	testArray (s5);

	for ( int i = 0; i < 25; i++)
		cout << s5[i];

	return 0;
}

void testArray ( char *s5 )
{
	s5 = new char [20];
	char s1 [11] = "Hello ",
		 s2 [11] = "my "	,
		 s3 [11] = "name's " ,
		 s4 [11] = "Rob";

		strcat(s5,s1);
		strcat(s5,s2);
		strcat(s5,s3);	
		strcat(s5,s4);
}


Also does strlen count the null terminator?
Last edited on
closed account (10X9216C)
I'd recommend using std::string, it'll make your life much much easier.

You are just passing the value to testArray, changing the value of s5 in testArray doesn't modify s5 in main. You need to either make it a reference to the pointer or make it a pointer to a pointer.

Or just return it:

1
2
3
char* test() { return new char[10]; }

char* s5 = test();
Topic archived. No new replies allowed.