0

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?

2
  • 1
    *file is the same as file[0]. It's the single first character in the string. Commented Jan 9, 2023 at 10:45
  • @Someprogrammerdude Oops, sorry I forgot about that C feature. Thanks. Commented Jan 9, 2023 at 10:48

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.