array: pass by reference

hi,

im having trouble tryng to pass my array into a function. so here is the deal. i made an array of let say unsigned char. but i dont know the size of the array, so i just put it as a pointer. then i send this pointer to a function that will fill the array with known size. offcourse after it set the size of the pointer. after the method called, i want the pointer that i just created before is the array that filled. basically the code is like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using namespace std;

void testArray(unsigned char** array) {
	*array = (unsigned char*)malloc(3);

	assert(*array);
	*array[0] = 'a';
	*array[1] = 'b';
	*array[2] = 'd';
}
int main ()
{
	unsigned char * array;
	testArray(&array);
	std::cout << array[0];
}


but its not working. when i try to fill the array, it gives me error bad access or something.

if i do it as an ordinary array:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void testArray(int* array) {
	array = new int[3];
	array[0] = 1;
	array[1] = 2;
	array[2] = 3;
}


int main ()
{
	int * array;
	testArray(array);
	std::cout << array[0];
}



it prints the wrong value: -1073743920, which is i think is an adress, -1073743920.

is there a way to get send a pointer as a reference, set as an array in the function, and then called later on the main function?


thanks in advance.
*array[0] is the same as *(array[0]), not (*array)[0].
In the second code you aren't changing the value of array (the direction to which points)
Either pass it by reference or return the value
1
2
void testArray(int *&array);
int * testArray();
Topic archived. No new replies allowed.