Home > OS >  Automatic generation of struct printing function in C
Automatic generation of struct printing function in C

Time:01-21

I have many programs where structs are defined. And each time, I have to create a function to print the members. For example,

typedef struct {
    char name[128];
    char address[1024];
    int zip;
   } myStruct;


void printMyStruct(myStruct myPeople) {

  printf("%s\n",myPeople.name);
  printf("%s\n",myPeople.address);
  printf("%d\n",myPeople.zip);
}

int main()
{
   myStruct myPeople={"myName" , "10 myStreet", 11111};

   printMyStruct(myPeople);
}

I know that reflection is not supported in C. And so, I write these printing functions for each struct I defined.
But, I wonder if it exists any tricks to generate automatically these printing functions. I would understand that I have to modify a little bit these functions. But, if a part of the job is done automatically, it would be great. (This example is simple, sometimes struct are nested or I have array of structs or some fields are pointers, ...)

CodePudding user response:

You can of-course print structs, but expect a lot of non-readable output:

#include <stdio.h>
#include <ctype.h>

struct example {
     int x;
     int y;
     char c;
};

#define NOT_PRINTABLE "Not Printable"

void print_structure(const char *structure, size_t size) {
     for (size_t i = 0; i < size; i  ) {
          printf("%ld)\t%.2X: %.*s\n", i, structure[i], 
                (isprint(structure[i]) ? 1 : sizeof(NOT_PRINTABLE) - 1),
                (isprint(structure[i]) ? &structure[i] : NOT_PRINTABLE));
     }
}

int main(int argc, char **argv) {
     struct example a;
     a.x = 5;
     a.y = 6;
     a.c = 'A';
     print_structure((char *)&a, sizeof(struct example));

     return 0;
}

But the issue is that, it will print the structs as it is represented in memory. So 4 byte (32 bit) integer 1 will be represented with 4 bytes, not the char '1'.

And due to the way pointers work, you cannot make out if a member is a pointer or a non-pointer.

Another issue is that structures have padding to help with alignment, and better/efficent use of memory. So you would see a lot of 0x00 in the middle.

Remember that C is a compiled language.

CodePudding user response:

let's consider to use https://copilot.github.com/. it's great. this is what i have with copilot

typedef struct {
    char name[128];
    char address[1024];
    int zip;
   } myStruct;

//print struct myStruct  >> auto generate by codepilot after you type a comment `print struct myStruct`
void printStruct(myStruct *s) {
    printf("name: %s\n", s->name);
    printf("address: %s\n", s->address);
    printf("zip: %d\n", s->zip);
}
  •  Tags:  
  • Related