1

I am trying to dynamically allocate memory for a 3d character array I am calling

buffer

As it is right now, my code looks like:

char buffer[50][50][20]

Eventually I will need to work with over thousands of spots in this array based on the number of rows and number of columns being read through a CSV file. I save those variables as:

numCol;
numRow;

My program finds these perfectly through a function and returns them back to main() where I want to use them to create my 'buffer'.

How do I allocate space using malloc(), or other means, to create a buffer that takes the form:

 char buffer[numCol][numRow][20]. 

The 20 can stay because that is what I define as the maximum number of characters in a CSV cell.

  • And the line you paste does not work? It should. – Hans Petter Taugbøl Kragset Aug 30 '17 at 12:34
  • like [this](https://ideone.com/Sp6Pdo) – BLUEPIXY Aug 30 '17 at 12:56
  • 1
    I wrote an answer, while it got closed. In short: you can use `char (*buffer)[numRow][20] = malloc(sizeof(char[numCol][numRow][20]));`. – mch Aug 30 '17 at 12:57
  • Starting with an example for a 2D (x,y) grid of ints , (1) allocate a chunk of memory for all the cells themselves as int (so sizeof(int) * x * y). (2) Allocate a chunk of memory for pointers (int *) to every Yth cell (3) Use the address of that 2nd chunk (which is an int **) as addr[x][y]. Once that makes sense, extend to 3D, which will have a third layer of pointers and be an (int ***). – Alex North-Keys Sep 04 '17 at 21:38
  • Free()ing that would take several free()s - if that bothers you, combine everything into the first malloc()ed chunk, but be careful to keep pointers and ints at proper alignments. Malloc by default will align chunks this way, but being too clever can put your pointers at, say, not-multiple-of-8-byte alignment or something. Much like trying to access integers at odd-addresses tending to instantly crash programs on many architectures. – Alex North-Keys Sep 04 '17 at 21:45

0 Answers0