Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Word given to the standard in using scanf isn't printed without error

Tags:

c

I am trying to printf a simple string but I am not being able to.

#include <stdio.h>

int main(){
   char *word;
   scanf("%s", &word);
   printf("%s\n", word);
   return 0;
}
 

When I insert the word my code breaks.

It just stops the program execution but doesn't give me any error.

What am I doing wrong?

like image 667
Miguel Matos Avatar asked Nov 28 '22 21:11

Miguel Matos


1 Answers

Problem 1: you need to allocate space for your word.

Problem 2: Your scanf() syntax is incorrect for a character array.

Problem 3: scanf("%s", ...) itself is susceptible to buffer overruns.

SUGGESTED ALTERNATIVE:

#include <stdio.h>

#define MAXLEN 80

int main(){
   char word[MAXLEN];
   fgets(word, MAXLEN, stdin);
   printf("%s", word);
   return 0;
}
like image 69
paulsm4 Avatar answered Dec 15 '22 15:12

paulsm4