Return array from function

Hey guys,

My homework question code wants me to print 100 random lower case letters. I did everything. I just need help from returning the values stored in my lowercaseletters[100] array to the main function. When I get 100 random lower case letters to my createarray() function, they are right. but when I return them to the main, I get garbage values etc.What could be the problem?

I just get this warning when I compile my code

 
[Warning] address of local variable 'randomletters' returned [-Wreturn-local-addr]


this is my code

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
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <ctime>
#include <cmath>
#include <cstdlib>

using namespace std;

const int NUMBEROFLETTERS=100;

char getrandomlowercaseletter()
{
	int temp;
	char randomletter;
	temp = rand()%26;
	randomletter = static_cast<char>(temp + 'a');
	cout << randomletter;
	return randomletter;
}

char *createarray()
{
	int temp;
	char randomletters[100];
	srand(time(NULL));
	for (int i=0; i<100; i++)
	{
		randomletters[i] = getrandomlowercaseletter();
	
	}
	
	return randomletters;        //here is where I need help.
} 



int main()
{
	

char *chars=createarray();

for (int i=0; i<100 ; i++)
{
	cout << *(chars+i);
}

return 0;	
}
Within the function createarray, you create an array. When the function ends, all the variables within it created on the stack (which means anything you didn't create using new) are abandoned. The memory is free to be reused.

So you are keeping hold of a memory address (i.e. the pointer you return) to some memory that used to hold an array. That memory is free to be reused, and probably will be.

I suggest you create the array in main, and have your createarray function (which you should rename to something like fillArray) fill it with random values. You'll have to pass a pointer to the start of the array to this function, and you should probably also tell it how big the array is.

I commend you on having that warning turned on, and for reading it. It should make more sense now; you were creating a local variable inside the function (the array) that will cease to exist when the function ends, and returning the address of it (the pointer to it), hence the warning.
Last edited on
Topic archived. No new replies allowed.