1

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?

apomene
  • 14,282
  • 9
  • 46
  • 72
Eleftheria
  • 13
  • 1
  • 4

3 Answers3

0

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
Sergey L.
  • 21,822
  • 5
  • 49
  • 75
  • 3
    This is actually wrong at multiple levels: First the array is uninitialized and points to nothing so you really cannot assign anything to its contents. So you need one extra alloc. Second, you should use `calloc(sizeof(int), N)` for the rows. – Stefan Arentz Oct 22 '13 at 12:31
0

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.

Zild
  • 61
  • 1
  • 4
0

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.

Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144
Sebastien
  • 1,439
  • 14
  • 27