Thread: Convert data from file into a matrix

  1. #1
    Registered User
    Join Date
    Nov 2007

    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:
                   void main(){
                    int c;
                    fp = fopen(mapa,"r");				
    	if (fp == NULL){
    	printf("Can't open %s\n",mapa); 
                    c = getc(fp);
                    while(c != EOF ){
    		c = getc(fp); 
    now, someone told me that i should do this:

                     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??
    thanks in advance,
    i really would appreciate it

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    > 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).
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    lfs addicted
    Join Date
    Nov 2007
    Quote Originally Posted by Salem View Post
    > 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 subscribe to a feed

Similar Threads

  1. Replies: 48
    Last Post: 09-26-2008, 03:45 AM
  2. matrix class
    By shuo in forum C++ Programming
    Replies: 2
    Last Post: 07-13-2007, 01:03 AM
  3. Weird errors.
    By Desolation in forum C++ Programming
    Replies: 20
    Last Post: 05-09-2007, 01:10 PM
  4. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  5. archive format
    By Nor in forum A Brief History of
    Replies: 0
    Last Post: 08-05-2003, 07:01 PM