AllAnimals AllAnimals - 1 year ago 97
C Question

Filling a *char[] with user input

Im am trying to implement the following c code:

int row, col;
scanf("%d %d", &row, &col);

char *map[col];

for(int i = 0; i < row; i ++){
scanf("%s", map[i]);

Where the user enters two numbers on the same line to declare the size of rows and columns of the array. Then the user will proceed to enter each row which will be stored. An example input would look like this:

10 12

But when I run my code I get a segmentation fault. Any suggestions?

I am not able to use char map[][] as other functions in the program use *char[].

Answer Source

But when I run my code I get a segmentation fault.

It's because the array map is uninitialized (which is undefined behaviour).

Initialize it with calls for malloc() or calloc() for each of the pointers in the map array. or just use a VLA which also defines the rows: char map[row][col];.

If you decide to use VLAs, be aware that they may not work for large size of row and col as they are allocated on automatic storage (aka "stack") and are only optional feature since C11.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download