I'm a newbie to c programming. I'm trying to input two strings using scanf
. My first try was as below
#include <stdio.h>
int main(void)
{
char *word1;
char *word2;
scanf("%s", word1);
scanf("%s", word2);
printf("%s\n", word1);
printf("%s\n", word2);
}
If I run this code, only the first input is correctly stored (word2
is null). But, if I run the code below, both inputs are correctly stored in word1
and word2
.
#include <stdio.h>
int main(void)
{
char word1[10];
char word2[10];
scanf("%9s", word1);
scanf("%9s", word2);
printf("%s\n", word1);
printf("%s\n", word2);
}
What is the problem with using pointers with scanf
?
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\n", word1);
printf("%s\n", word2);
// once done with allocated memory, free it
free (word1);
free (word2);
return 0;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments