简体   繁体   中英

Passing 2D array of pointers of string array to function in C

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 ie 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.

You should allocate memory to first_array using malloc and then do your desired operation .

Like this -

first_array=malloc(sizeof(char *)*2);       // here used 2 as you need 2 pointer right now
for(int i=1;i<3;i++){
      for(int j=0;j<2;j++){
            first_array[i][j]=malloc(strlen(string)+1);
      }
  }

Note- But remember to free allocated memory. And also don't declare it global if not necessary.

With your first declaration char *first_array[20][20] , you are creating a global 2d array, and allocating memory for it, to the part of the memory that global variables are stored.

So you have an array of pointers, but were are they pointing at? You then have to allocate memory for your strings, and give to the pointers in your array an address to a string location.

You can not use strcpy() because your pointer is not pointing to anything yet, it may hold a garbage value though and so producing a segfault trying to access a memory address that doesn't exist or is used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM