Like Tree2Likes
  • 1 Post By Adak
  • 1 Post By laserlight

Multidimensional Array Malloc

This is a discussion on Multidimensional Array Malloc within the C Programming forums, part of the General Programming Boards category; Hello I am making my CPU burn hell and crash everytime I run this program, so there is some error ...

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    18

    Multidimensional Array Malloc

    Hello

    I am making my CPU burn hell and crash everytime I run this program, so there is some error either an infite loop or I dont know what, but it is meant to just assign on the fly from user input the number of rows, cols, and then i just fill content and print to see I did alright, but obviously, I didnt.

    I d really appreciate if anybody could pinpoint where I am messing

    Here it goes:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    
    
    
    
    int main()  {
    	
    int **mat; // Pointer to pointer
    
    
    int rows, cols, i, j, k;
    
    
    printf("How many rows you want ");
    scanf("%d", &rows);
    
    
    mat = (int **)malloc(rows*sizeof(int*)); // array of number of rows
    
    
    printf("How many cols ");
    scanf("%d", &cols);
    fflush(stdin);
    for (i=0; i<rows; i++)  // for each row ...
    {
     	
     	mat[i] = (int *)malloc (cols * sizeof(int)); // add these many cols
    }
    
    
    for (j = 0; j<=rows; j ++)
      {
     	
     	for (k = 0; k<=cols; k++)
     	{
     	
     	mat[j][k] = j * k;
     	
     	printf("so the values for the array ar %d: ", *(*(mat+j)+k));
     	
        }
        
     }
    	getchar(); 
    	
    }

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,592
    > fflush(stdin);
    This is undefined behaviour - see the FAQ.
    Also in the FAQ are some notes about not casting the result of malloc.


    > for (i=0; i<rows; i++) // for each row ...
    > for (j = 0; j<=rows; j ++)
    What is different about these two loops?
    Which one is correct for accessing the elements of an array?
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Remove the = in your for loops stop check:
    Code:
    for(j=0;j<rows;j++)
       for(k=0;k<cols;k++) 
          //etc.
    The last valid element of an array, is NumberOfElementsInThatDimension - 1. That is true for every dimension, of the array.

    rows - 1
    cols - 1
    depth - 1 //if it were a 3D array
    etc.
    Last edited by Adak; 09-30-2011 at 07:02 AM.
    alvarito likes this.

  4. #4
    Registered User
    Join Date
    Sep 2011
    Posts
    18
    Thank you, I overlooked that evidence. That avoided the crashing and seems to deliver the right values, I ll have a look at them but so far it pretty much allows me to examine results. Thanks a lot

    best regards

    Al

  5. #5
    Registered User
    Join Date
    Sep 2011
    Posts
    18
    Yes, I know what you mean, but in my development environment (windows and Dev C++, but I am moving to Linux asap) if I dont include that function, then the execution finishes right after the scanf, it does not go beyond and the console disappears before i get a chance to examine it.

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Same basic program, just improved a bit.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(void)  {
       int **mat; // Pointer to pointer
       int rows, cols, i, j;
    
       printf("How many rows do you want? ");
       scanf("%d", &rows);
       getchar(); //remove newline from input stream
    
       //rows = 10;
       //cols = 10;
    
       mat = malloc(rows*sizeof(int*)); // array of number of rows
    
       printf("And how many columns? ");
       scanf("%d", &cols);
       getchar(); //removes the left over newline
     
       for (i=0; i<rows; i++) { // for each row ...
          mat[i] = malloc(cols * sizeof(int)); 
       }
       for (i = 0; i<rows; i++) {  //assign some test values
     	   for (j = 0; j<cols; j++) {
     	      mat[i][j] = i * j;
     	      //printf("%4d ", mat[i][j]); //same as below line of code
                  printf("%4d ", *(*(mat+i)+j));
          }
          putchar('\n');
       }
       //free rows:
       for(i=0;i<cols;i++)
          free(mat[i];
       free(mat);     
       
       printf("\n\n"); 
       getchar(); //hold the terminal window open
       return 0;
    }
    Last edited by Adak; 09-30-2011 at 09:53 AM. Reason: forgot to free the allocated memory!

  7. #7
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,794
    When you want a rectangular 2D array, another option to consider is to create a huge array of the objects that you want, then create another array of pointers to point to these objects at regular intervals. You then access this second array as a 2D array of the objects that you want. The advantage here is that you would only need to allocate memory twice. Building on Adak's example:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void) {
        int *data;
        int **mat;
        int rows, cols, i, j;
    
        printf("How many rows do you want? ");
        scanf("%d", &rows);
        getchar(); /* remove newline from input stream */
    
        printf("And how many columns? ");
        scanf("%d", &cols);
        getchar(); /* removes the left over newline */
    
        /* Lazy, so assume that malloc always succeeds */
        data = malloc(rows * cols * sizeof(*data));
        mat = malloc(rows * sizeof(*mat));
        for (i = 0; i < rows; i++) {
            mat[i] = data + (i * cols);
        }
    
        /* Assign and print some test values */
        for (i = 0; i < rows; i++) {
            for (j = 0; j < cols; j++) {
                mat[i][j] = i * j;
                printf("%4d ", mat[i][j]);
            }
            putchar('\n');
        }
    
        /* Done, so cleanup */
        free(mat);
        free(data);
    
        printf("\n\n");
        getchar(); /* hold the terminal window open */
        return 0;
    }
    Adak likes this.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  8. #8
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    ^^^^ Very interesting, Laserlight!

  9. #9
    Registered User
    Join Date
    Aug 2010
    Posts
    231
    Code:
        scanf("%d", &rows);
        getchar(); /* remove newline from input stream */
        /* this is not safe, test it, if you put a non-digit char: scanf will stop on this and getchar eat this, '\n' keeps in input buffer */
        /* better is always: */
        while(getchar()!='\n');
        ...

  10. #10
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,515
    Code:
          printf("so the values for the array ar %d: ", *(*(mat+j)+k));
    This line is just begging for an error in pointer arithmetic. Just access you're 2-D array as a 2-D array:
    Code:
          printf("so the values for the array ar %d: ", mat[j][k]);
    Also note, you don't actually need k. It's a better idea to reuse i and j, keeping their usage consistent (i for rows, j for cols).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with MultiDimensional Array (I think)
    By RommelTJ in forum C Programming
    Replies: 5
    Last Post: 11-25-2009, 01:30 AM
  2. 2d multidimensional array
    By epica in forum C Programming
    Replies: 2
    Last Post: 08-20-2009, 04:43 PM
  3. help with multidimensional array
    By keira in forum C++ Programming
    Replies: 4
    Last Post: 10-30-2008, 11:28 AM
  4. Copy multidimensional array to single array?
    By seepox in forum C Programming
    Replies: 9
    Last Post: 05-08-2006, 11:19 AM
  5. multidimensional array and malloc
    By Kinasz in forum C Programming
    Replies: 4
    Last Post: 12-20-2003, 01:15 PM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21