5

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?

Marievi
  • 4,951
  • 1
  • 16
  • 33
K.H.A.J.A.S
  • 514
  • 4
  • 19

3 Answers3

11

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.

Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606
  • why this is ok for inner struct? say the detial – BlackMamba Apr 27 '16 at 08:20
  • @BlackMamba What? The location of the `typedef` doesn't matter here, I just prefer to not clutter the global scope. – unwind Apr 27 '16 at 08:22
  • You move `typedef struct { const int x, y; } A;` to the inner of `int main(){}` – BlackMamba Apr 27 '16 at 08:24
  • @BlackMamba Yes, but that's just since it's a local thing, and this program has just `main()`. No need to make things global that don't have to be global. – unwind Apr 27 '16 at 08:35
  • But why this one works while OP's code throws a compilation error? (On my machine no errors are thrown when compiling OP's code) – nalzok Apr 27 '16 at 09:53
-1

You can't. With POO in C you can disable the modification of those fields, if you:

  • define getters: char A_get_x(A *p); and char A_get_y(A *p);
  • define the struct in the .c to hide its implementation
  • only write typedef struct A A; in the .h file, to allow to use that type.
  • define a constructor : A *A_new(); which returns A with the values desired on x and y.

By doing this, you can only modify the values in the constructor, and after the object is created the values wont change (if you dont force the values with pointers etc..)

-1

First, you should use malloc to allocate the size of the struct, not a magic number 2. Also, don't cast malloc return value, it is automatically promoted to the compatible pointer type.

a1 = malloc(sizeof(A));

Second, there isn't really not much use to make struct member const.

A *a1;
a1 = malloc(sizeof(A));

a1's members are not initialized to any state here, yet the compiler forbidden any assignments to them, since it is defined as const, so a1->x = 'a'; won't compile.

A a2;
a2->x = 'a'; // won't compile too

The only valid use case is:

A a3 = {'a', 'b'};
fluter
  • 13,238
  • 8
  • 62
  • 100