# Thread: Convert data from file into a matrix

1. ## Convert data from file into a matrix

hey there
i need to convert data from a certain file into a matrix, in order to that matrix be a "labirinth" (i'm working on a project that trys to simulate a labirinth game)
my objective here is to read a file, get his content, and then pass it to a matrix that i have denominated as "char * * matrix;"
so, i'm gonna show you my code so you can understand better:
Code:
```
void main(){

int c;
fp = fopen(mapa,"r");
if (fp == NULL){
printf("Can't open %s\n",mapa);
exit(0);
}
c = getc(fp);
while(c != EOF ){
putchar(c);
c = getc(fp);
}```
now, someone told me that i should do this:

Code:
```                 matrix = (char **)malloc(nr_lines * sizeof(char*));
for (line = 0; line < lines; line++){
matriz[line] = (char*)malloc(nr_columns * sizeof(char*));
} // don't worry, i've already denominated lines, columns etc```
so, after this, if this 2nd code is right, my matrix positions (x / y) will be the same as the file i've read?
if not, what better way should i do??
i really would appreciate it

2. > void main()
main returns an int, not void.
See the FAQ

> matriz[line] = (char*)malloc(nr_columns * sizeof(char*))
Another FAQ point, don't cast the result of malloc in a C program.
Also, the sizeof expression is wrong, it should be just char.

In fact, use this approach when using malloc
p = malloc( numRequired * sizeof *p );
It always works, and you never have to refer back to the declaration of p in order to work out the type. Instead, you make the compiler do it (much safer).

3. Originally Posted by Salem
> void main()
main returns an int, not void.
See the FAQ
I was expecting something like "see my avatar" :-D
(ok, I stop posting useless stuff)

Popular pages Recent additions