0

I am trying to experiment a thing in C to print the Structure field with the user input

Ex:

typedef struct 
{
  int A;
  int B;
  int C;
  char str[50];
} my_struct;

void print ( struct my_struct *hndl , char* str )
{
  /* Not sure how to implement this */

}

int main ( argc, argv[] )
{
   my_struct hndl = { 1 , 2, 4, "hiall" };

   print ( &hndl, "A" ) //should print the value of A which is 1;
   print ( &hndlm "str" ) //should print the value of str which is hiall 
}

I understand that C doesnt support reflection , but just wondering there might be some other way around. In real, I have my structures really complex with all data types, arrays, pointers but want to start with the above little structure.

Thanks.....

vip
  • 53
  • 1
  • 6
  • Likely beyond your present stage of C coding, yet something like `GPrintf("A: ", GP(hndl.A), "str: ", GP(hndl.str), GP_eol);` as used [here](http://codereview.stackexchange.com/q/115143/29485) will work. – chux - Reinstate Monica Apr 04 '17 at 18:09
  • Example `GPrintf("A: ", GP(hndl.A), " str: <", GP(hndl.str), ">", GP_eol);` printed `A: 1 str: `. In general [Reflection support in C](http://stackoverflow.com/q/1353022/2410359) is possible, yet not trivial to implement. – chux - Reinstate Monica Apr 04 '17 at 18:25
  • Else just use `printf("A: %d str: <%s>\n", hndl.A, hndl.str);` Post additional info to add clarity/specificity to your coding goals - it is quite general at this point. – chux - Reinstate Monica Apr 04 '17 at 18:42
  • Thanks a lot Chux. The above links are really helpful. – vip Apr 04 '17 at 18:54
  • Could you please point me where the GP_format is defined? May be i missed it or overlooked – vip Apr 04 '17 at 23:48
  • `GP_format[]` is part of code I wrote in `GPrint.h` [here](http://codereview.stackexchange.com/q/115143/29485). – chux - Reinstate Monica Apr 05 '17 at 01:29

0 Answers0