0

I have an integer variable x that I need to use to make two 2D arrays but I get an error of "cannot allocate an array of constant size 0". After doing some research I apparently need to use malloc but I have no idea how to apply it to my currently situation.

My two arrays I need:

int firMat[x][5];
int secMat[5][x];
4
  • Are you set a value to a variable x before this? Commented Oct 12, 2014 at 21:31
  • @BLUEPIXY Yes, a value is assigned to x before this. Commented Oct 12, 2014 at 21:32
  • 1
    Do your C Compiler support C99? Commented Oct 12, 2014 at 21:34
  • @BLUEPIXY I'm using Visual Studio Pro. 2013 and from what I've read it only uses parts of C99. Commented Oct 12, 2014 at 21:36

3 Answers 3

1
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int x = 2;
    int **firMat;//int firMat[x][5];
    int **secMat;//secMat[5][x];
    int i;

    firMat = malloc(x * sizeof(int*));
    for(i = 0; i< x; ++i)
        firMat[i] = malloc(5 * sizeof(int));

    secMat = malloc(5 * sizeof(int*));
    for(i = 0; i< 5; ++i)
        secMat[i] = malloc(x * sizeof(int));

    //do stuff E.g. fir[2][1] = 21;
    //release E.g.
    //for(i = 0; i< x; ++i)
    //    free(firMat[i]);
    //free(firMat);

    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you're using C99, this will work. It will create a "variable-length array", sadly VLAs have been reduced to "optional" in C11.

To use malloc for this, typically I'd abandon the double-array notation, and treat the memory as a flat one-dimensional array, then array[i][j] becomes ptr[ i*cols + j ].

Comments

0

Try to initialize x like in the example below

#define x 2 //outside the function

and then use x like this

int firMat[x][5];
int secMat[5][x];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.