Passing Array to function

beginner stuff but i dont know why its not working correctly.
This is only passing my array as 4 items instead of 9.

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
#include <iostream>
using namespace std;

void Output(char MyArray[]);
int main()
{
	const int Size = 9;
	char MyArray[Size] = {'!', '"', '#', '*', '-', '.', '@', '|', '~'};
	Output(MyArray);
	system("PAUSE");
	return 0;

}
void Output(char MyArray[])
{
	int Num = sizeof(MyArray);
	cout << Num;
	for (int x = 0; x < Num; x++)
		for (int y = 0; y < Num; y++)
		{
			cout << MyArray[x];
			if (y == Num-1)
				cout << "  " << MyArray[x] << endl;
		}
}


this line is only outputting 4 instead of 9.... my size should be 9... why is it not passing my array as the size that is made in main?

1
2
int Num = sizeof(MyArray);
	cout << Num;

this line:
 
void Output(char MyArray[])

is equivalent to this:
 
void Output(char *MyArray)

"MyArray" in function Output is not an array, it's pointer (and size of any pointer, no matter of which type, is 4 bytes)
To print arrays in c++ functions, you must pass one more value to the function, and it's array's size
this would be correct function:
1
2
3
4
5
6
7
8
9
10
void Output(char MyArray[], int Num)
{
	for (int x = 0; x < Num; x++)
		for (int y = 0; y < Num; y++)
		{
			cout << MyArray[x];
			if (y == Num-1)
				cout << "  " << MyArray[x] << endl;
		}
}

and now u call funtcion like this
 
Output(MyArray, sizeof(MyArray));


Notice that in function, you don't work with copy of array, u just have pointer to it, and then u're able to move through array with it
Last edited on
(and size of any pointer, no matter of which type, is 4 bytes)

This size depends on the CPU and operating system you are using. The value may often be 8 or sometimes higher.
Be careful!
Output(MyArray, sizeof(MyArray));

This only works well because the arrays element size is 1.

A more general way to calculate the number of an arrays elements may be by using a macro ARRAYSIZE which is defined as follows:

#define ARRAYSIZE(a) (sizeof(a) / sizeof(*(a))) // Calculate the number of items of array `a´
Topic archived. No new replies allowed.