Home > database >  How to use malloc to assign large 2d arrays in c
How to use malloc to assign large 2d arrays in c

Time:02-11

I know very large 2 dimension arrays in c need the long identifier for the variable type when assigning memory to the array to avoid stackoverflow errors and memory issues, supposed I intend to assign memory to my matrix A which should hold a very large number of numbers using malloc, how am I supposed to go about it...

int main(){
int rows=20000;
int cols=20000;
//how do I define the 2d array using long int
long long int** A=new long long int(rows);
//I got that from this site but it's wrong how do I go about it
}

CodePudding user response:

Use pointers to array:

int main()
{
    size_t rows=20000;
    size_t cols=20000;

    long long int (*A)[cols] = malloc(rows * sizeof(*A));

    //You can use it as normal array.
    A[6][323] = rand();
}

or (but access has different syntax)

int main()
{
    size_t rows=20000;
    size_t cols=20000;

    long long int (*A)[rows][cols] = malloc(sizeof(*A));

    //You can use it almost as normal array.
    (*A)[6][323] = rand();
}
  • Related