1

I have a file of strings seperated by space and I want to get those strings into an array of defined type but I get an error saying that fscanf doesn't take char**, does anyone know how to do this please?

typedef struct{
      char *string;
      int name;
      } DBZ;

DBZ Table[100];

fp = fopen("text.txt", "r");
if(fp == NULL)
{
    fprintf(stderr, "Error opening file.");
    exit(1);
}
else {
    int i=0;
    while(!feof(fp))
    {
        fscanf(fp,"%s", &Table[i].string);
        i++;
    }
}

3 Answers 3

2

&Table[i].string

You're taking an address of a pointer, which is a pointer-of-a-pointer, which is a char**

Also,

fscanf provides no functionality to allocate the memory you need. You'll have to malloc a block large enough to hold whats in your file. Then you'll want to use something safer than fscanf, preferable the most secure thing available* to make sure you don't overwrite the buffer.

else {
    int i=0;
    while(!feof(fp))
    {
        Table[i].string = malloc(100);
        fscanf_s(fp,"%s", Table[i].string, 100);
        i++;
    }
}

* These are Microsoft extensions, your platform may have something different.

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

4 Comments

The safer_than_fscanf link may not be applicable to his platform though.
In the first line, you mean char **.
Also, to make sure you don't read more than a certain number of characters, you could give "%100s" for example as format string. Unfortunately, unlike printf, you can't give "%*s" and give that number as an integer.
And if you're using extensions, the GNU C Library has an allocation flag to the %s conversion. %as I believe. That will return an allocated string pointer. Not recommended for portable code though.
0

You need to allocate space for char *string in your struct. And your %s takes char* not char**

Comments

0

Remove the &, Table[i].string is already a pointer.

string also needs to contain memory. You could change the definition of your struct to:

typedef struct{
      char string[90];
      int name;
} DBZ;

That assumes that your data will fit in 90 bytes. Depending on what your data is, it could also be a very inefficient way of storing it. malloc(), as others have pointed out, could help you here.

Comments

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.