Print structure fields and values ​​in C

I am interested in printing structure fields.

Typedef struct
{
   UINT32 thread_id;
   BOOL   is_valid;
}T_THREAD;

Is there a C way to print the contents of a structure, something like

ex: print (T_THREAD)and the output should look like

Contents of a structure T_THREAD are 
  thread_id
  is_valid
+4
source share
4 answers

What you are looking for is a reflection. Java and other virtual languages ​​are reflected, so you can print variable names and function names for any given class. Because the compiler automatically creates these reflection functions.

C is not reflected. You must do everything manually.

+6
source

As for your structure, the function will look something like this.

// st_name is the name of the struct
void print(T_THREAD *st, const char *st_name)
{
    printf("Contents of structure %s are %lu, %d\n", st_name, st->thread_id, st->is_valid);
}
+3
source

, / .

, , , , , , , . -

T_THREAD var;

my_print(var);  //my_print() is the function you'll roll out

.

, , , "".

+2

printf. C . :

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct {
    char *name;
    int thread_id;
    bool is_valid;
}T_THREAD;

int
main(void) {
    T_THREAD T1 = {"T1", 123, 1};
    T_THREAD T2 = {"T2", 456, 0};

    printf("\nContents of a structure %s are:\n", T1.name);
    printf("thread_id: %d\n",T1.thread_id);
    printf("is_valid: %d\n", T1.is_valid);

    printf("\nContents of a structure %s are:\n", T2.name);
    printf("thread_id: %d\n",T2.thread_id);
    printf("is_valid: %d\n", T2.is_valid);

    return 0;
}

:

Contents of a structure T1 are:
thread_id: 123
is_valid: 1

Contents of a structure T2 are:
thread_id: 456
is_valid: 0

Alternatively, you can also create a function for this:

int
main(void) {
    T_THREAD T1 = {"T1", 123, 1};
    T_THREAD T2 = {"T2", 456, 0};

    print_struct_elements(&T1);
    print_struct_elements(&T2);

    return 0;
}

void
print_struct_elements(T_THREAD *T) {
    printf("\nContents of a structure %s are:\n", T->name);
    printf("thread_id: %d\n",T->thread_id);
    printf("is_valid: %d\n", T->is_valid);
}
+1
source

Source: https://habr.com/ru/post/1664698/


All Articles