开发者

file of strings into array in C

I have a file of strings seperated by sp开发者_JS百科ace 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++;
    }
}


&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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜