Following is my code, I want to use pointer to pointer to store strings.
char **BlankWords(char word[]){
// take word 'lad' as an example
// length of it is 3
// fill in blank: _ad, l_d, la_, _lad, l_ad, la_d, lad_
// 3 + 4 = 7
// which means, length of 'lad' + (length of 'lad') + 1
int strLength = strlen(word);
char **blank_words = malloc(sizeof(char*) * (2 * strLength + 1));
assert(blank_words != NULL);
int i, j, k;
for (i = 0; i < strLength; i++){
// allocate memory for each length of the word
blank_words[i] = calloc(MAX_WORD_LENGTH, sizeof(char));
assert(blank_words[i] != NULL);
char temp[MAX_WORD_LENGTH];
strcpy(temp, word);
temp[strLength] = '\0';
temp[i] = '_';
blank_words[i] = temp;
// printf("%s\n", blank_words[0]);
}
for (j = strLength; j < (2 * strLength + 1); j++){
// allocate memory for each length of the word
blank_words[j] = calloc(MAX_WORD_LENGTH, sizeof(char));
assert(blank_words[j] != NULL);
char temp[MAX_WORD_LENGTH];
strcpy(temp, word);
temp[(strlen(temp) + 1)] = '\0';
for (k = (strLength - 1); k >= (j - strLength); k--){
if (k >= 0){
temp[k + 1] = temp[k]; // in order to insert '_' to the word, then the other letter move back one
}
}
temp[j - strLength] = '_'; // insert '_' to the word
blank_words[j] = temp;
}
return blank_words;
}
Following is the output, each row was overwritten after each loop, but in my opinion, each row cannot be overwritten, and may store a unique string.
blank_words[0]: lab_
blank_words[1]: lab_
blank_words[2]: lab_
blank_words[3]: lab_
blank_words[4]: lab_
blank_words[5]: lab_
blank_words[6]: lab_
I don't know why the previous data gets overwritten after each loop. In my opinion, the output should be:
blank_words[0]: _ab
blank_words[1]: l_b
blank_words[2]: la_
blank_words[3]: _lab
blank_words[4]: l_ab
blank_words[5]: la_b
blank_words[6]: lab_
char temp[MAX_WORD_LENGTH]; blank_words[i] = temp;That results in Undefined Behaviour.tempis a local variable within the scope of theforloop. Which means the variable is invalid outside the loop and using a reference to it outside the loop is UB. One option isblank_words[i] = strdup(temp);. That allocates dynamic memory so don't forget tofreeit when done.free?free. The caller of this function would free the memory when it no longer needs the array and its contents.