I wanted to know if its possible to declare a 2D array in c even if we dont know the size. I tried doing it like this
char **array; //2D array of characters - global
int length, height; // - global
and then in a function declare the size like this
void size_and_data(){
int i;
//some more code here
array=(char**)malloc(sizeof(char*)*height); //height and length are
//given from a file
for(i=0;i<length; i++)
array[i]= (char*)malloc(sizeof(char)*length);
//more code to follow..
}
Also at this point my array is full of characters and i printed every single one to make sure they are stored correcly. However if i try to access the elements while being in another function im getting a segmentation fault. This is how i try to access them:
void access_f(){
int i,j;
for(i=0; i<height;i++){
for (j=0;j<length; j++)
printf("%c", array[i][j]);
}
}
Keep in mind there aren't any more function involved in between so the array doesn't change in any way. Should this be happening? I thought global variable keep their values untill the programm stops running.
I'm new to c and any help would be greatly appreciated!
Thanks!