Thread: How to allocate memory in multidimensional array?

1. How to allocate memory in multidimensional array?

If you want to save memory space, you use pointer together with malloc or calloc functions to allocate memory for the desired string instead of using predeclared array.

Question:
How do I actually do the same thing in a multidimensional array without predeclare it i.e multi[4][10] for instance?

2. Pointer arithmatic kinda breaks down once you get into multi-dimensional arrays. Although maybe this will be helpful...
Code:
```char s[10];
char s2[4][10];
s = "Chicken"; // waste
s2[0] = "Chicken"; // Ditto
s2[1] = "Cow";
s2[2] = "Moose";
s2[3] = "Homo Erectus"; // impossible```
Okay, obviously that's bad. Here's how you'd do it with pointers...
Code:
```char * s;
char * s2[4];
s = "Chicken"; // leet
s2[0] = "Chicken"; // ditto leet.
s2[1] = "Cow";
s2[2] = "Moose";
s2[3] = "Homo Erectus";```
Actually, I'm not sure that the prior code will work, although if it does, then that seems to be pretty much what you're looking for.

3. Thank you very very very much, pal!!

Eventhough, the example that you gave me is simple but it gave me a pretty wide idea on how this allocating stuff works on multi-dimensional array. Thank you again and thanks for your anticipation!!

4. Or you could also look into malloc(), realloc(), calloc() and free() functions. Those functions give you a lof of flexibility to handle memory allocations for any array that you would like to create. But you must make sure to free() the memory, otherwise you will have "memory leaks".

5. free() to free memory. You must do that! Can't stress enough. MUST! Or bad things happen.

6. For a 2d array of size
char iarray[3][10];
really the 3 is a row and the 10 is a column:

Code:
```#include<stdio.h>
#include<stdlib.h>

int main()
{
char **iptr = (char **) malloc (sizeof(char*) * 3);
for(int i = 0;i < 3; i++)
iptr[i] = (char *) malloc (sizeof(char) * 10);

strcpy(iptr[0], "Chicken");
strcpy(iptr[1], "Cow");

printf("%s  %s", iptr[0],iptr[1]);
return 0;
}```

7. Code:
```	for(i=0;i<3;i++)
free(iptr[i]);```
Should mention how to free the array.