Im able to find the most frequent letter, but when trying to print the elements in **words again, Im given \000 values.
I tried to store head into another variable but seems like I still lose all reference.
I also tried to pass it as a constant but I still lose reference. void findFrequentLetter(const char **words)
and also modified the call with const. How can I make this work?
I know the problem is in the first for(while()) loop.
void findFrequentLetter(char const **words) {
int array[255] = {0}; // initialize all elements to 0
char str[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int i, max;
for (int d = 0; d < nb_words; d) {
while (**words != '\0'){
array[**words];
(*words);
}
words;
}
// Find the letter that was used the most
max = array[0];
int index = 0;
for (i = 0; str[i] != 0; i ) {
if (array[str[i]] > max ) {
max = array[str[i]];
index = i;
}
}
}
CodePudding user response:
This is wrong:
for (int d = 0; d < stats->mot_sans_doublons; d)
{
while (**words != '\0')
{
array[**words];
(*words); // <===== HERE
}
words;
}
Your code is given the base address to an array of pointers. Each of those pointers refers to a string. The line in question above advances the pointers in that array... permanently. The underlying array of pointers has each pointer within that array permanently walked to the end of their respective strings.
The correct way to walk those strings is by intermediate pointer. Do NOT modify the content of words
in any way. For example:
for (int d = 0; d < stats->mot_sans_doublons; d)
{
for (const char *s = words[d]; *s; s)
array[(unsigned char)*s];
}
Whether the rest of your code 'works' I leave to you, but that is the reason why, after calling your frequency counter, your words array seems to have "lost its references".