user12050586
user12050586

Reputation:

Printing variable-type struct elements

I have created a struct to store variable-type elements:

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

enum TYPES {TYPE_STRING, TYPE_NUMBER};
struct Value {
    void * value;
    int type; 
};

int main(int argc, char *argv[]) {


    // add element one
    struct Value val1;
    val1.value = "Hello";
    val1.type = TYPE_STRING;
    printf("Struct1: {value: %s | type: %d}\n", (char *) val1.value, val1.type);

    // can also initialize it like this
    struct Value val2 = {.value = "goodbye", .type = TYPE_STRING};
    printf("Struct2: {value: %s | type: %d}\n", (char *) val2.value, val2.type);

    // how to initialize a number though?
    int number = 2;
    struct Value val3 = {.value = &number, .type = TYPE_NUMBER};
    printf("Struct2: {value: %d | type: %d}\n", (int) val3.value, val3.type);

}

Yet for some reason value3 doesn't print properly.

main.c:26:46: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
Struct1: {value: Hello | type: 0}
Struct2: {value: goodbye | type: 0}
Struct2: {value: -531387940 | type: 1}

What would be the proper way to print this? I've also put it here: https://onlinegdb.com/S17HrvNPB

Upvotes: 1

Views: 131

Answers (1)

Mihir Luthra
Mihir Luthra

Reputation: 6769

printf("Struct2: {value: %d | type: %d}\n", *((int *) val3.value), val3.type);

This should do the job.

A void * holds an address of any type. You have stored &number in it. Now if you want to print it, first of all you need to access that address. You can't access an address that is stored in void * without typecasting. This is because, compiler won't understand how many bytes at that address need to be accessed. void * just points to the starting of that address.

So to tell the compiler that we need to access sizeof(int) bytes, we first typecast it into (int *) and then to get the value at that address, we do *((int *) val3.value).

Here consider reading more about void *:
What does void* mean and how to use it?

Upvotes: 2

Related Questions