问题
How do I make a 2d dynamic array (in C) with specific row number and different column size in each row?
For example: This is an array (3=rows)
|1 | 4 | 5 |
|3 |
|6 | 2 |
1st row - 3 columns
2nd row - 1 column
3rd row - 2 columns
I want my program while running to ask the user for every row to give the number of cols. How do I make an array like this?
回答1:
If you want something dynamic and don't care about constant access time, you can create an array of linked list, otherwise you have no choice but to allocate some space with sufficient memory and keep it updated with realloc.
回答2:
What you will probably want to is to use a pointer pointer and allocate sufficient memory for each row then. Example:
int ** array = calloc(sizeof(*array), NUMROWS);
array[0] = calloc(sizeof(**array), 3); // 3 fields
array[1] = calloc(sizeof(**array), 1); // 1 field
array[2] = calloc(sizeof(**array), 2); // 2 fields
回答3:
You need an array of pointers:
int *ptr_array[3];
Then for each row, you need to allocation memory:
int map_array[3] = {3,1,2}
int i;
for(i = 0; i < 3; i++){
ptr_array[i] = malloc(sizeof(int)*map_array[i]);
}
If you need the number of row to be dynamic, you should do the first part as:
int **ptr_ptr_array;
(*ptr_ptr_array) = malloc(sizeof(int *)*3);
Good luck with recycling the memory.
来源:https://stackoverflow.com/questions/19517639/2d-dynamic-array-in-c-with-specific-row-number-and-different-column-size-in-ea