I'm writing a function, which receives an empty array of pointers, the amount of words the the function should scan at most(size) (btw it can scan less than size amount of words), and the maximum length of a word(which I should ensure a word doesnt surpass).
Here is my code (I'm using C & the lines with arrows give an error):
void read_words(char* words[], int size, int max_str_len)
{
int i=0;
while( (i<size ) && (scanf("%s", & *words[i]) != EOF ))
{
1-> if(strlen(*words[i]) > max_str_len )
{
2-> *words[i][max_str_len-1] = '\0';
}
}
}
after getting a bunch of errors I realised that the errors come from the fact that the pointers array only points to the first char of the sequence (meaning only the first letters of the words).
(the first line arrow also gave mr the following error: error: passing argument 1 of 'strlen' makes pointer from integer without a cast)
So the question is, how can I fix it? how do I get the entire word or get to the end of it? if I change it to " *words[i] + max_str_len " does it fix the problem? but in that case I might get the value of a different variable sitting in the memory...
any help is much appreciated :)
i<sizefirst and thenscanf().*words[i].strlen()does not look like C. Did you meanstrlen(words[i])?'/0'certainly should be'\0'.max_str_lenis (one greater than) the maximum number of characters that eachwordcan hold. If you write more than that number into each word (whichscanfwill happily do), the behavior will be undefined. Attempting to truncate the string after the fact by writing a null character at the end will not avoid the problem.array[index], not*array[index]as you're doing everywhere in your code.