Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't make structure's field as constant in C

When I declare structure given below, it is throwing compilation error.

typedef struct{
    const char x; //it is throwing compilation error
    const char y;
}A;

void main()
{
    A *a1;
    a1 = (A*)malloc(2);
}

How can I make structure's field (characters x and y) as constant?

like image 257
K.H.A.J.A.S Avatar asked Apr 27 '16 08:04

K.H.A.J.A.S


1 Answers

That should be fine, but of course you can't assign to them, only use initialization.

So it doesn't make a lot of sense to allocate an instance on the heap.

This works:

#include <stdio.h>

int main(void) {
    typedef struct {
        const int x, y;
    } A;
    A my_a = { 12, 13 };
    printf("x=%d\ny=%d\n", my_a.x, my_a.y);
    return 0;
}

It prints:

x=12
y=13

Also, please don't cast the return value of malloc() in C.

like image 175
unwind Avatar answered Sep 19 '22 22:09

unwind