What is the problem with using pointers with scanf?
The first one is undefined behaviour. Look at this part of code:
char *word1;
char *word2;
scanf("%s", word1);
scanf("%s", word2);
No memory allocated to word1
and word2
pointers. When you give input, scanf()
end up accessing unallocated pointers and dereferencing an unallocated/invalid pointer is undefined behaviour.
You should make sure that before using/accessing a pointer, it should be pointing to a valid memory location. You can either make it point to an exiting valid memory or allocate memory dynamically to it, like this:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *word1;
char *word2;
word1 = malloc (10);
if (word1 == NULL) {
exit (EXIT_FAILURE); // or whatever you want to do to handle memory allocation failure
}
word2 = malloc (10);
if (word2 == NULL) {
exit (EXIT_FAILURE); // or whatever you want to do to handle memory allocation failure
}
scanf("%9s", word1);
scanf("%9s", word2);
printf("%s
", word1);
printf("%s
", word2);
// once done with allocated memory, free it
free (word1);
free (word2);
return 0;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…