Returning char array from function

I made a program to build a game board of a set size, but now I want to add asking the player how large they want the game board to be. So to make an array that can later be used to make the game board I've come up with:

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
#include "stdafx.h"
#include <iostream>
#include <new>
using namespace std;

char *creatingarray (int& height, int& width, char* dynamic)
{
	int boardsize;
	boardsize = height*width;
	int i;
	for (i=0; i<height; i++)
		for (i=0; i<width; i++)
			dynamic[boardsize] = '-';
	for (i=0; i<boardsize; i++)
                cout << dynamic[boardsize];
	cout << endl;
	return dynamic;
}
int main()
{
	int height;
	int width;
	char *y;
	cout << "What do you want the height of the room to be?\n" << endl;
	cin >> height;
	cout << "\n";
	cout << "What do you want the width of the room to be?\n" << endl;
	cin >> width;
	cout << "\n";
	int boardsize;
	boardsize = height*width;
	char *dynamic = new char [boardsize];
	y = creatingarray (height, width, dynamic);
	cout << y << endl;
    system ("pause");
    return 0;
}


However, when I run the program and put in 5 for height and 5 for width, the first line I want printed out displays the correct array of '-' 25 times and then the cout << y << endl; prints out a bunch of gibberish. My understanding is that the array is localized in the function, so once the function returns something the array is destroyed, so the pointer that is returned is pointing to who knows what. Going with that I noticed that if I put everything in int main () it runs completely fine, but I'm trying to figure out how to do this by using functions. I also know that I can return a string, but I'm not just trying to print out the array, I'm trying to return the contents of the array as char elements so I can do stuff with them later.
As you defined 'y' as the pointer to char then the operator << outputs all characters until it encounters a zero-character.
Right. I'm thinking that it should output all characters in the array correctly, but it doesn't. It prints out a bunch of random characters that make no sense. It prints out:
═════════════════════════-²²²½½½½½½½½■ε■
when what I want the array to contain is:
-------------------------

So, what is happening/ what can I do to my code to make it work? Or is returning the all of the elements of an array not possible? Or maybe i'm going about this the wrong way?
Last edited on
I would use a two-dimensional array because you deal with height and width.

To output the array you should output each its element separatly.

For example

1
2
3
4
5
6
7
8
for ( int i = 0; i < height; i++ )
{
   for ( int j = 0; j < width; j++ )
   {
      std::cout << y[i * width + j];
   }
   std::cout << std::endl;
}
Topic archived. No new replies allowed.