Creating Variable-size 2D Arrays

Discussion in 'C' started by nickld, Mar 19, 2008.

  1. nickld

    nickld New Member

    Mar 19, 2008
    Likes Received:
    Trophy Points:
    I'm writing a program in C to multiply two user-inputted matrices and am having a little bit of trouble initializing the input arrays...

    Basically, the program starts with the user inputting the dimensions of each matrix (matrix1 and matrix2) and then these values are stored as integers in the variables rowsize1, columnsize1, rowsize2, columnsize2.

    I now want create these two matrices... However I cannot do this with matrix1[rowsize1][columnsize2] and matrix2[rowsize2][columnsize2] as this is illegal in C!

    I read that variable-size arrays can be created in C by using the "malloc" function but I'm not entirely sure on how to implement it in my case...

    For the first matrix (matrix1) would I have to do something like this:

    int **matrix1;
    matrix1 = (int**)malloc(columnsize1*sizeof(int*));

    for(a = 0; a < rowsize1; ++a)
    matrix1[a] = (int*)malloc(sizeof(int));

    I'm not really sure though...

    Any help would be much appreciated!!

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice