不能使结构的字段在C中保持不变

K.H*_*A.S 5 c structure constants

当我声明下面给出的结构时,它会抛出编译错误.

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

void main()
{
    A *a1;
    a1 = (A*)malloc(2);
}
Run Code Online (Sandbox Code Playgroud)

如何使结构的字段(字符xy)保持不变?

unw*_*ind 11

这应该没问题,但当然你不能分配它们,只能使用初始化.

因此,在堆上分配实例没有多大意义.

这有效:

#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;
}
Run Code Online (Sandbox Code Playgroud)

它打印:

x=12
y=13
Run Code Online (Sandbox Code Playgroud)

另外,请不要malloc()在C中转换返回值.