I want to dynamically allocate a 2d array to store strings.
I originally declared the array like this:
char lines[numlines][maxlinelength];
This however gives me a stack overflow when numlines is very huge.
How can I dynamically allocate it to prevent stack overflow?
- 
 arr = malloc(numlines[star]maxlinelength[star]sizeof(char));Martin James– Martin James2016年04月01日 11:16:03 +00:00Commented Apr 1, 2016 at 11:16
 
3 Answers 3
Use a pointer to an array:
#define maxlinelength 10
char (*lines)[maxlinelength] = malloc( sizeof( char[maxlinelength] ) * numlines ) ;
lines[0][0] = 'A' ;
This requires that the inner most size, maxlinelength, is constant.
You can avoid this limitation if you use pointers to variable-length arrays in which case the syntax remains the same and maxlinelength doesn't have to be a constant. Standards that supports this feature, are C99 and optionally C11.
( A constant is a variable whose value is known at compile time.)
( And to clarify: sizeof( *lines ) is identical to sizeof( char[maxlinelength] ) )
Comments
Try this code:
char **arr;
int i;
arr = malloc(numlines*sizeof(char*));
for (i = 0; i < numlines; i++)
 arr[i] = malloc(maxlinelength*sizeof(char));
This will give you a pointer to pointer, but you can handle it as if it was a 2D array.
Also see this very useful link in order to understand what dynamic allocation for 2D arrays actually does in the memory.
14 Comments
int (*p)[varcols] = malloc(...);You may allocate a contiguous block of memory with the following:
const int numlines = 10;
const int maxlinelength = 120;
const int arrlen = sizeof(char) * numlines * maxlinelength;
const char **lines = (const char**)malloc(arrlen);
fprintf(stderr, "Allocated %d bytes\n", arrlen);
Add/remove const and typecasting according to taste.
1 Comment
lines[i] does not point to (the first character of) an array of char, so lines[i][j] doesn't work as if it is accessing a 2D array.Explore related questions
See similar questions with these tags.