I am trying to create a table of strings with 20 rows and 20 columns. It has following functions.
Insert values to cells in table
Concatenate 2 rows and replace to another row
Modify values in table
and some more operations
To do that I am trying to declare, pass and modify 2d strings i.e 2D array of char pointers. This is what I did. Below code contains only small portion of my code.
char *first_array[20][20]; //declared 2d array of pointers for storing a table of strings
int modify(char *array1[], char *array2[]) //here i want to pass 2 rows row 1 and row 2
{
int result1 = strcmp(array1[1], "~"); // here i want to access row 1 1st column for string operation
int result2 = strcmp(array2[1], "$");
return result1+result2;
}
int main() {
char *string = "hello";
strcpy(first_array[1][0], string); // insert values into table
strcpy(first_array[1][1], "~");
strcpy(first_array[2][0], string);
strcpy(first_array[2][1], "~");
printf("the result is %d\n", modify(first_array[1], first_array[2]); // pass row1 and row2
return 0;
}
Is this code correct ? Because Initially I was getting the error
expected ‘char **’ but argument is of type ‘const char **’
But I somehow corrected it and now I am getting segmentation fault. I am not able to get expected result.
Please provide me proper code for declaring, accessing, modifying and passing to functions of 2d array of char pointers/strings in C for above scenarios.
first_arraybefore usingstrcpyusingmallocor just assign instead ofstrcpy. Note that you aren't supposed to modify the string if you are assigning. And don't forget to includestdlib.handfreethe allocated memory if you are going formalloc.