0

main() won't loop when input from scanf() is empty (nothing happened when I hit "Enter" key after the "prompt" printed out in the shell. It's a truncated version of what I was trying to build. Very new to C, could really need some help!

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>


int main(){

    char string1;
    printf("prompt");
    scanf("%s", string1);
    if(!string1){
        return main();
    }
    printf(" %s", string1);
    return 0;
}
tkausl
  • 13,686
  • 2
  • 33
  • 50
  • 2
    A `char` is not a string. – tkausl Sep 24 '17 at 20:06
  • would it work if I use char string[10] instead? – Z. Winter Sep 24 '17 at 20:09
  • You should always check the function `scanf` return value too. Anyway `string1` is *uninitialised* so testing its value is useless if `scanf` fails. – Weather Vane Sep 24 '17 at 20:10
  • @Z.Winter It would at least scan it. Anyway, I'm not entirely sure what are you trying to do with `if (!string1)`. Actually, I have no idea what you're trying to do with `if (!string1)`. – MarkWeston Sep 24 '17 at 20:10
  • "would it work if I use char string[10] instead" it might but you could be a victim of a buffer overflow exploit. Are you following a tutorial course or guessing? – Weather Vane Sep 24 '17 at 20:11
  • @MarkWeston The if statement was supposed to be testing if string1 is NULL of not; not sure if it's the legitimate way of doing it. – Z. Winter Sep 24 '17 at 20:31
  • @Weather Vane I guess a little bit both, being following tutorial and online searching non-stop for the project. – Z. Winter Sep 24 '17 at 20:33

0 Answers0