I want to create an array of 26 word arrays (to sort my lists of words by first letter) so I believe I allocated memory accordingly but when I try a test run and attempt to set a random word, "hi", to each spot which must have a word, it only works for the first 5 letters then returns a set fault. Pardon my code or description, I'm quite the beginner. HELP
Note: both my parameters are defined in external functions, wordArray is the array of words in a given text file, numWordsPerLetter is an integer array which holds the number of words that start with each letter of the alphabet.
char*** create_alphabetical_array(char** wordArray, int* numWordsPerLetter){
char*** alphabeticalArrays;
int i, j;
alphabeticalArrays = malloc(sizeof(char**)*26);
for (i = 0; i < 26; i++){
printf("%d\n", numWordsPerLetter[i]+1);
alphabeticalArrays[i] = malloc(sizeof(char*)*numWordsPerLetter[i]+1);
}
for (i = 0; i < 26; i++){
for (j = 0; j < (numWordsPerLetter[i]+1); j++){
printf("%d %d %d\n", i, j, numWordsPerLetter[i]+1); /* using to help debug */
strcpy(alphabeticalArrays[i][j], "hi");
}
}
return (alphabeticalArrays);
}
At least these 2 errors:
Wrong element size and wrong n
. alphabeticalArrays[i]
is a char **
, so sizeof(int)
is amiss. element_size * numWordsPerLetter[i]+1
should be element_size * (numWordsPerLetter[i]+1)
Better to use p = malloc(sizeof *p * n)
, then p = malloc(sizeof *(type-of p) * n)
. Easier to code right, review and maintain.
// alphabeticalArrays[i] = malloc(sizeof(int)*numWordsPerLetter[i]+1);
alphabeticalArrays[i] = malloc(sizeof alphabeticalArrays[i][0] * (numWordsPerLetter[i]+1));
// ^---Element size--------------^ ^-------------N--------^
strcpy(alphabeticalArrays[i][j], "hi");
fails because alphabeticalArrays[i][j]
is not assigned a pointer to allocated memory for the string "hi"
. @Zelnes
alphabeticalArrays[i][j] = malloc(strlen("hi") + 1);
Alternative: research strdup()
.
Robust code would also check if the allocations succeeded.
p = malloc(n);
if (p == NULL) Handle_Failure();
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.