'Double Dynamic Array
This is my first time working with dynamic arrays and I am honestly just so confused. My original array(below) works fine.
#include <stdio.h>
int main()
{
char icdC[4][10];
for(int i =0;i<4;i++){
for(int j=0;j<10;j++){
printf("What are your ICD codes [%d][%d]\n",i,j);
scanf("%s", &icdC[i][j]);
}
}
return 0;
}
However I tried converting this array into a double dynamic array (below) it doesn't seem to work correctly as it will either tell me "signal: segmentation fault (core dumped) or it just won't run.
#include <stdio.h>
#include <strings.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>
int main()
{
char** icdC;
icdC = (char**)malloc(4*10*sizeof(char));
for(int i=0;i<4;i++){
for(int j=0;j<10;j++){
printf("What are your ICD codes [%d][%d]\n",i,j);
scanf("%s", &icdC[i][j]);
}
}
return 0;
}
Solution 1:[1]
The issue seems to be located within icdC = (char**)malloc(4*10*sizeof(char));, as it is an incorrect reference to the second array you're trying to create.
In C there are many options to represent a 2d array, among which the possibility to
create an array of pointers, each of which points to a specific row. Then you can allocate the memory for each array using the malloc, which allows you to generate an "array of pointers".
The implementation would most likely be:
char ** icdC;
int r = 4, c = 10;
icdC = (char*) malloc(sizeof(char*) * r);
for (int i = 0; i < r; i++) {
icdC[i] = malloc(sizeof(char) * c);
}
Note: You can also do this implementation in two loops as you did above.
From here you can do a nested loop to scan the value like you've already done in your snippet. Remember that now you can access a value by indicating the index for the corresponding row and column, like this: icdC[row_num][row_column] = .....
It might look strange at the beginning, but after you get a grasp of the concept, it's all good and fun!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | lemon |
