How to cast string array created by calloc, back into string array?

Viewed 47

In below sample code, under GDB, I want to watch a dynamically created string array as a typical string array:

// dynamically create an array of 2 strings, each string has 21 characters.

char **word_list = calloc(2, sizeof(char*));

word_list[0] = calloc(1, sizeof(char) * 21);
word_list[1] = calloc(1, sizeof(char) * 21);

strcpy(word_list[0], "foo");
strcpy(word_list[1], "bar");


// statically create an array of 2 x 21 as a comparison
char word_list2[2][21] = {{'f','o','o'},{'b','a','r'}};

In GDB, is there way to cast word_list into a character array so that I can watch its content the same way as watching word_list2:

(char[2][21]) word_list // this cast shows a bunch of gibberish. 

word_list1, a 2 x 21 string array created dynamically, showing gibberish when viewed this way word_list1, a 2 x 21 string array created dynamically, showing gibberish when viewed this way

word_list2, a typical string array of 2 x 21

word_list2, a typical string array of 2 x 21

1 Answers

An array of char * is not the same as an array of char[21]. So they appear different because they are different.

You can change your code to allocate memory for an array of arrays and assign it to a proper array type:

char (*word_list)[21] = calloc(2, sizeof(char[21]));
Related