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?
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;
}
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(unsignedint 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.