-2

I want to declare a large 2D (50,000x 50,000) char array in C. Can we do that ? And if yes how ?

underdog_eagle
  • 25
  • 1
  • 1
  • 5
  • 1
    Read about `dynamic memory allocation`. – Jyothi Babu Araja Jan 10 '17 at 05:52
  • [check this link](http://www.geeksforgeeks.org/dynamically-allocate-2d-array-c/) – 0xtvarun Jan 10 '17 at 06:00
  • You can 1. Use dynamic memory allocation or 2. declare the array as a global. It is unlikely that such a large memory can work on the stack. – Rishikesh Raje Jan 10 '17 at 06:09
  • If 46340 is big enough try `char a[46340][46340];` outside of main() – Marichyasana Jan 10 '17 at 06:29
  • 2
    The only thing special about this example is the size (a shade above 2GB). It's the question about allocating a 2D array or something to do with the size? If the size, can you be clearer as to what isn't working? – levengli Jan 10 '17 at 06:40
  • It is the size. For a square matrix I use sqrt(2^31). Allocating it outside of main() puts it in the heap rather than on the stack (I think.) – Marichyasana Jan 10 '17 at 07:30
  • Actually I have to take that back as I tried to run such a program and it didn't run properly on my Win 10 64-bit. The declaration does get past an error from the compiler so I just assumed it would run. Use the dynamic methods suggested by others. – Marichyasana Jan 10 '17 at 07:53
  • a 50000x50000 char array is almost 2.5GB and 10GB for int. In most cases you won't need that much memory for a beginner or intermediate problem. You're probably overthinking and use an algorithm with high complexity (e.g. O(N²) instead of a much more efficient like O(log N)) and your program might never finish in enough time. Or it might be solved with sparse arrays – phuclv Jan 10 '17 at 09:07
  • This might very well be an [XY problem](http://meta.stackexchange.com/q/66377/230282). Show what your real problem is – phuclv Feb 25 '17 at 13:06

1 Answers1

0
int **array;
int i;

array = (int**)malloc(sizeof(int*) * 50000)// <stdlib.h> for malloc

for (i = 0; i < 50000; i++)
   array[i] = (int*)malloc(sizeof(int) * 50000);

You can then access the elements as array[i][j].

unwind
  • 391,730
  • 64
  • 469
  • 606
Petok Lorand
  • 955
  • 6
  • 15
  • 6
    [Please consider omitting the cast of `malloc()`'s return value in C](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). Also, that does 50,001 heap allocations which is hardly optimal or very nice. It can be trivially simplified to do 2, and with a tiny bit of work you can just do a single allocation. – unwind Jan 10 '17 at 08:55
  • 1
    At least it's large enough, by a pretty wide margin: `sizeof int` to be precise. OP asked for a mere `char` array. – Jongware Jan 10 '17 at 08:58
  • 2
    Why are you making arrays of `int` when the question is about `char`? – Tom Zych Jan 10 '17 at 11:08