Passing arrays by reference

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>

void allocatearray( char ** &matrix)
{
int i,j;
matrix = new char*[ 10000];
for (i=0; i < 10000; i++)
{
matrix[i] = new char[ 26];
for (j=0; j < 26; j++)
{
matrix[i][j] = NULL;
}
}
}
int main()
{
char** dictionary;
allocatearray(dictionary);
int wordRow = 0;
FILE * inFile;
inFile = fopen ("textfile.txt","r");
while ( fgets (dictionary[wordRow] , 26 , inFile) != NULL )
{
wordRow++;
}
system ("pause");
return 0;
}

As you can see I'm trying to dinamically allocate an two dimentional array and populate it with words from text file.(doing it in C, not C++) However, when I compile, I get this error:

"expected ';', ',' or ')' before '&' token " (in declaration of "allocatearray")

Can anyone please explain to me what i'm doing wrong?
char** &matrix says that "matrix" is reference to a pointer to a pointer to char. But C has no references, so the C compiler throws that error.

To do this In C, you'll need to either take a triple pointer, or return a double pointer.
Last edited on
How is it done? In class, my teacher just showd us the C++ way, and about C he said "send with an ampersand, catch with an aserisk, use with an asterisk"
After this brief explanation I still have no idea how to do it in C.
Ok, so I fixed it up a little. It comples now without errors but the program crashes right away. I think because of some memory segmentation fault or something like that. Can you please take a look at it? I think I'm making a mistake somewhere with pointer arithmetic.

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
void allocatearray( char *** matrix)
{
int i,j;
(**matrix) = (char**)malloc(sizeof(char**));
for (i=0; i < 10000; i++)
{
(*matrix[i]) = (char*)malloc(sizeof(char*));
for (j=0; j < 26; j++)
{
*matrix[i][j] = '0';
}
}
}
int main()
{
char ** dictionary;
allocatearray(&dictionary);
int wordRow = 0;
FILE * inFile;
inFile = fopen ("textfile.txt","r");
while ( fgets(dictionary[wordRow],26,inFile) != NULL )
{
wordRow++;
}
system ("pause");
return 0;
}
Anybody can help me with my pointer arithmetic?
as your topic say . passing array by reference

in c++
array are always pass with reference even without ampersand
Your allocation function looks wrong to me. To allocate arrays of multiple dimensions, you do something like this:
1
2
3
4
5
int** arr; // we will make this dynamically arr[SIZE1][SIZE2]
arr = malloc(sizeof(char*) * SIZE1);
for(unsigned int i = 0; i < SIZE1; ++i) {
    arr[i] = malloc(sizeof(char) * SIZE2);
}

Your allocator seems to be trying to deference matrix twice before you've even allocated the outer rows of the array.
Topic archived. No new replies allowed.