Home > front end >  Scanning input into a malloc pointer not working
Scanning input into a malloc pointer not working

Time:01-10

I have this code but it's not working. No matter what I type it prints nothing.

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



char *askFile()
{
    printf("Enter a file: ");
    char *file = malloc(512 * sizeof(char));
    scanf("%s", file);

    return file;
}



int main()
{
    char *file = askFile();
    printf("%s", *file);


    return 0;
}

Why doesn't it work?

CodePudding user response:

As @Someprogrammerdude said in the comments the mistake was:

printf("%s", *file);

It was supposed to be:

printf("%s", file);

Since *file points to the first element.

CodePudding user response:

The key mistake is not using a good compiler with all warnings enabled. A good well-enabled compiler would have warned about the specifier-type mismatch.

char *file =...;
printf("%s", *file); // Warning expected.

Save time. Enable all compiler warnings.

  • Related