This small piece of code takes a user input and returns the last word from the user input.
I don't exactly understand how those 2 lines of code work
can someone explain why or how printf( &last_word[i]);
when I is at position 0 prints the last word of the sentence entered by the user input.
the purpouse of the program is to print the last word of the user input, but I dont understand those lines of code, If I change something on those 2 lines, the code stops working and it doesnt return the last word entered by the user.
#include <stdio.h>
int main(){
int i = 0;
char *last_word;
char str[800];
printf("enter:");
fgets(str,100,stdin);
while (str[i] != '\0') {
if (str[i] == ' ' && str[i + 1] > 32)
last_word = &str[i + 1];
i++;
}
/*------------------------these next lines of code-----------------------*/
/*-----> i = 0;
/*-----> printf( &last_word[i]);
return 0;
}
Holy undefined behavior batman.
The while loop stuffs the address of the next character past a space character into last_word
; thus if there are any space characters it points one past the last one.
i = 0
therefore &last_word[i]
is the same as last_word
. So it uses the last word as a printf
format string.
But that's not the same as last word. Try this input: " %n%n%n%n%n%n%n%n". Goodbye.
The first argument to printf
should almost always be a constant. You want printf("%s", last_word);
In fact, let us put it this way; the only reason to ever not pass a constant format string to printf
and friends is your standard library is too old to support %*d
for dynamic widths.