0

I wrote this code that reads from a .txt a string and settles it in a char *, but it gives me error that the variable "string" is not initialized, even if i initialized it inside the fscanf, can u tell me where i wrong? Thanks!

    char *string;
    FILE *fp = fopen("words.txt", "r");
    fscanf(fp, "%s", string);
11
  • 2
    You must allocate some space to string. Commented Jun 10, 2015 at 12:51
  • 1
    well, if i dont know how is long the string in the txt file? How i allocate enough space for it? Thanks Commented Jun 10, 2015 at 12:54
  • string is a pointer to char. You've to make it point to a char array(char buffer[100]; string = buffer;) or dynamically allocate memory(string = malloc(100); and after use, free(string);) before you write to it from the fscanf. Commented Jun 10, 2015 at 12:54
  • If you don't know how long the text is then you have options. One is to figure out a maximum, 4096 is a common one used for a maximum line length. Second, don't use fscanf, use fread where you can specify the maximum number of bytes to read. That's a bit more work, but safer. Commented Jun 10, 2015 at 12:58
  • @wing , In that case, you can use getline if you can. It allocates the right amount of memory. Commented Jun 10, 2015 at 13:00

2 Answers 2

4

That's normal, you didn't allocate string. C needs you to allocate it in memory before you use it. Also you will have to know its size.

In your code, string points to nowhere into memory so it doesn't exist (to be exact it points to somewhere you have a lot of chance that you can't access it)

See how malloc works.

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

Comments

1

Allocate space for the string with malloc function.

string=malloc(100*sizeof(char));

3 Comments

BTW, malloc is a function. "malloc statement" is a wrong statement.
Perhaps you could explain where the 100 comes from?
I just used 100 as an example.We can allocate as much memory as we feel safe to work with.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.