0

I know a very large two-dimensional arrays in C needs a long identifier for the variable type when assigning memory to the array to avoid stack overflow errors and memory issues. Suppose 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 two-dimensional
    // 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?
}
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
  • 1
    `new` is not a valid operator in C. Are you using C++? – mch Feb 10 '22 at 12:13
  • Whatever you think to know, it is not what you think it is. Large arrays require a large (enough) type for addressing elements. That does not mean you must use large elements. That is why `size_t` is used to query size of an element and to address an element. You can also create a huge array of single chars. – Gerhardh Feb 10 '22 at 12:15
  • In C++, `new long long int(rows)` allocates a *single* `long long int`, and initialize that single `long long int` to the value `rows`. – Some programmer dude Feb 10 '22 at 12:17
  • @mch, no am not using c , how to use malloc is the problem am updating the post though – Publius Flavius Tiberium Feb 10 '22 at 12:24
  • No am not using c plus plus, am using c instead –  Feb 10 '22 at 12:26
  • [**Correctly allocating multi-dimensional arrays**](https://stackoverflow.com/questions/42094465/correctly-allocating-multi-dimensional-arrays). I'll let others decide if this is a dupe. `long long int** A` will never refer to a 2-dimensional array. – Andrew Henle Feb 10 '22 at 12:27
  • @PubliusFlaviusTiberius If you're not programming in C, then why do your question say that you do? Or do you mean that you're not programming in C++? If you program in C++, then **[edit]** your question to reflect that (title, body, tags). But if you do program in C then you really need to get a book or take classes, as that should teach you all you need to know, and much more. – Some programmer dude Feb 10 '22 at 12:31

1 Answers1

3

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();
}
0___________
  • 47,100
  • 4
  • 27
  • 62