symtek
symtek

Reputation: 61

Pointer from Variable Name

I've defined nodes in a linked list with the letters A through H like so:

A = (struct node*) malloc(sizeof *A);

I scanf in a string which names the next node and the name of the variable to change it to. So if I write "0B", I want it to take the character 'B' and point to the object that has the variable name B:

state->zero = B;

without having to explicitly write a function where I have a series of if statements that convert the text input to the pointer output based on input.

How do I do this?

Upvotes: 0

Views: 210

Answers (1)

Mustafa Ozturk
Mustafa Ozturk

Reputation: 811

#include <stdio.h>

struct node
{
   char buf[16];
};

int main() 
{
   node A;
   node B;
   node C;
   node  D;
   node  E;
   node  F;
   node  G;
   node  H;
   char  c;    
   node *nodes[] = {&A, &B, &C, &D, &E, &F, &G, &H};


   printf("enter character (Q) to quit: ");
   while ((scanf(" %c", &c) == 1) && (c != 'Q')) 
   {
      if (c >= 'A' || c<='H') {
         node* mynode = nodes[c - 'A'];  
         printf("mynode %p\n", mynode);
      } else {
         printf("Invalid\n");
      }
      printf("enter character (Q) to quit: ");
   }
   return 0;
}

Upvotes: 2

Related Questions