Andrew
Andrew

Reputation: 434

Struct and variables in C

My struct looks like this:

struct Node
{
    int value;
    struct Node *A;
    struct Node *B;
    struct Node *C;
    struct Node *D;
    struct Node *E;
    struct Node *F;
    struct Node *G;
    struct Node *H;
    struct Node *I;
};

typedef struct Node *List;

And i'm trying to access one of "subnodes" via list->znak, where 'znak' is variable. However i'm getting error:

error: ‘struct Node’ has no member named ‘znak’

I don't know how to "tell" C that char is a variable.

I've written char, because "znak" mean char in my language.

Upvotes: 2

Views: 183

Answers (5)

CashCow
CashCow

Reputation: 31435

Your struct Node has 10 members, called value, A, B, C, D, E, F, G, H and I.

There is no member called znak.

What you are wanting is for "znak" to mean &Node::A and then later to mean &Node::B which you can actually do in C++ but not in C, after which you access it through operator ->* or .*

Of course just because it can be done doesn't mean it is the right thing to do and even if your code were C++ here I would suggest simply having an array (or in C++ a vector) of your node pointers after which you can simply pass in an index to the one you want to access presumably in each of your items.

Upvotes: 0

hugomg
hugomg

Reputation: 69934

In C, struct field names do not exist during runtime so you cannot convert a runtime character or string into a struct offset like you can in some scripting languages. In your case, I would use an array of Node * instead of having 10 separate fields.

struct Node
{
    int value;
    struct Node *children[9];
}

And to access the array you convert the characters to an array index by comparing them to the first character in your sequence.

struct Node* list = /*...*/;
int znak = 'D';
list->children[znak - 'A'] = /*...*/

Of course, once you start using an array instead of named fields, perhaps its going to be simpler to have znak be an integer index instead of a character in between A and I.

Upvotes: 7

tofutim
tofutim

Reputation: 23374

As others have stated, char is a reserved word in C. But additionally, the compiled code may not encode the letter of the node, since such names in a program are merely for human understanding. What you want to do is to use a hashtable or enums to assign the nodes, i.e., have an array of nodes.

Upvotes: 0

legends2k
legends2k

Reputation: 32894

There's no member named znak in the struct, hence the compiler won't allow you to use it as a member.

Upvotes: 0

Max
Max

Reputation: 2131

Char is a reserved word in the C language - you cannot define a variable named 'char' link

Upvotes: 0

Related Questions