dynamically creating an array in a function

Hey guys, thanks for taking the time to read this. I'm trying to create a simple program that dynamically creates an array in a function then returns it so i can use it in other functions. I know i have to do this with pointers, but they are extremely confusing to me. Any help would be greatly appreciated. The requirements for my program are, it uses an array, and the build_deck() function must be a void (if that's even possible?). Here's my code so far...

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
#include <iostream>

using namespace std;

void *build_deck();		// Builds the deck.

int main()
{
	int DECK_SIZE = 52;
	char *ptr;

	ptr = build_deck();

	for (int i = 0; i < DECK_SIZE; i++)
		cout << ptr[i] << endl;
	system ("PAUSE");
        return 0;
}

void *build_deck()
{
	char *arr;

	arr = new char [52];
	char arrays [52]= {'CA', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'C10', 'CJ', 'CQ', 'CK',
		'DA', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'D8', 'D9', 'D10', 'DJ', 'DQ', 'DK', 'HA', 'H2', 
		'H3', 'H4', 'H5', 'H6', 'H7', 'H8', 'H9', 'H10', 'HJ', 'HQ', 'HK', 'SA', 'S2', 'S3', 'S4', 
		'S5', 'S6', 'S7', 'S8', 'S9', 'S10', 'SJ', 'SQ', 'SK'};
	arr = arrays;
	return arr;


I know I can't return if I use a void, so how could I do this? Would I have to make the build_deck() a char? When I do that i get some weird characters when it couts the array. -Thanks, zrrz.
On line 29 you make arr point to arrays and you no longer have any way to delete the memory you allocated on line 24, causing a memory leak (you never tried to delete it anyway, though). Not only that, but arrays is destroyed on line 30, meaning that arr points to data that is almost certainly NOT what you want.

You need to use a for loop to copy the elements from arrays to arr rather than making arr point to arrays. Then you can return a character pointer instead of a void pointer and get the results you expect. ;)
Thanks. I understand the second part of what you said, but I'm a little confused about the first part. You're saying that I need to delete the memory i allocated on line 24? How would I do that?

EDIT: Thanks you so much, I got it all working.
Last edited on
http://www.cplusplus.com/doc/tutorial/dynamic/
See the part about Operators delete and delete[]
Topic archived. No new replies allowed.