How to initialize const in a struct in C (with malloc)

后端 未结 6 428
谎友^
谎友^ 2020-11-28 08:46

I have tried;

void *malloc(unsigned int);
struct deneme {
    const int a = 15;
    const int b = 16;
};

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


        
6条回答
  •  独厮守ぢ
    2020-11-28 09:28

    I disagree with Christ Dodd's answer, since I think his solution gives Undefined Behaviour according to the standards, as others said.

    To "work-around" the const qualifier in a way that does not invoke undefined behaviour, I propose the following solution:

    1. Define a void* variable initialized with a malloc() call.
    2. Define and object of the desired type, in this case struct deneme and initialize it in some way that const qualifier does not complain (that is, in the declaration-line itself).
    3. Use memcpy() to copy the bits of the struct deneme object to the void* object.
    4. Declare a pointer to struct deneme object and initialize it to the (void*) variable, previously cast to (struct deneme *).

    So, my code would be:

    #include 
    #include 
    #include 
    struct deneme {
        const int a;
        const int b;
    };
    struct deneme* deneme_init(struct deneme data) {
        void *x = malloc(sizeof(struct deneme));
        memcpy(x, &data, sizeof(struct deneme));
        return (struct deneme*) x;
    }
    int main(void) {
        struct deneme *obj = deneme_init((struct deneme) { 15, 20, } );
        printf("obj->a: %d, obj->b: %d.\n", obj->a, obj->b);
        return 0;
    }
    

提交回复
热议问题