0x6B6F77616C74
0x6B6F77616C74

Reputation: 2629

A struct defined in a separate header file

LMlib.h

#ifndef LMlib_H
#define LMlib_H
#endif

#define MAX_IP_LENGTH 15         
#define MAX_TABLE_ROWS 255

struct ForwardingTableRow
{
        char address[MAX_IP_LENGTH];
        int subnetMask;
        int interface;
};

typedef struct ForwardingTableRow ForwardingTableRow;

LMlib.c

#include <stdio.h>
#include <math.h>
#include "LMlib.h"

void ReadForwardingTable(FILE* f,ForwardingTableRow * table)
{
        int i;
        for(i=0;i<MAX_TABLE_ROWS;i++)
        {
                fscanf(f,"%s %d %d",&table.address[i],&table.subnetMask[i],&table.interface[i]);
        }


}

Complier command:

cc LMlib.c LMlib.h main.c -lm

Error:

LMlib.c: In function ‘ReadForwardingTable’:
LMlib.c:11:27: error: request for member ‘address’ in something not a structure or union
LMlib.c:11:45: error: request for member ‘subnetMask’ in something not a structure or union
LMlib.c:11:66: error: request for member ‘interface’ in something not a structure or union

What have I done wrong?

Upvotes: 1

Views: 408

Answers (2)

Bart Friederichs
Bart Friederichs

Reputation: 33491

It is all about operator precedence. . has a higher precedence than &, so basically it says:

  &(table.address)[i]

and table is not a struct, but a pointer to struct. Then, you are wrong in your indexing, you are indexing the struct's members, not the array.

Rewrite like this:

  table[i].address

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409136

You have three problems: The first is that you don't use the array indexing properly. It's the table variable that is the array, not the structure member:

fscanf(f, "%s %d %d",
    table[i].address,
    &table[i].subnetMask,
    &table[i].interface);

The second problem is unrelated to your question, but may lead to trouble in the future. It's the include guard you have. The #endif should be at the end of the file, otherwise you only protect the single #define and nothing else.

The third, and most serious, problem is that you have one character to little in the address field. The maximum length of an IP-address is 15, which is correct, but if you want to treat it as a string you need space for the string terminator as well. Declare it as

address[MAX_IP_LENGTH + 1];

and it should be okay.

Upvotes: 8

Related Questions