Suppose I have structure like:

typedef struct {
    int a;
    int b;
} my_struct;

Is there any way to get/print the name of the fields of that structure (i.e. "a" and "b")
programmatically?

Recommended Answers

All 2 Replies

No any member (variables, functionc etc) names at run time. Your running (compiled, linked and loaded) program is a block of machine commands and constants - an easy and healthy food for processor(s)...

Not without storing the names as strings somewhere:

#include <stdio.h>

typedef struct {
  int a;
  int b;
} my_struct;

const char * const my_struct_fields[] = {
  "a", "b"
};

int main()
{
  size_t n = sizeof my_struct_fields / sizeof my_struct_fields[0];
  size_t i;

  for (i = 0; i < n; ++i)
    printf("Field [%d]: %s\n", i, my_struct_fields[i]);

  return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.