【发布时间】:2012-03-30 06:56:08
【问题描述】:
我试过了;
void *malloc(unsigned int);
struct deneme {
const int a = 15;
const int b = 16;
};
int main(int argc, const char *argv[])
{
struct deneme *mydeneme = malloc(sizeof(struct deneme));
return 0;
}
这是编译器的错误:
gereksiz.c:3:17: error: expected ':', ',', ';', '}' or '__attribute__' before '=' token
还有,还有这个;
void *malloc(unsigned int);
struct deneme {
const int a;
const int b;
};
int main(int argc, const char *argv[])
{
struct deneme *mydeneme = malloc(sizeof(struct deneme));
mydeneme->a = 15;
mydeneme->b = 20;
return 0;
}
这是编译器的错误:
gereksiz.c:10:5: error: assignment of read-only member 'a'
gereksiz.c:11:5: error: assignment of read-only member 'b'
两者都没有被编译。使用 malloc 分配内存时,有什么方法可以在结构中初始化 const 变量?
【问题讨论】:
-
你必须抛弃 constness:
*(int*)(&mydeneme->a)=15; -
调用
malloc会导致未定义的行为,因为原型与库函数void *malloc(size_t);不兼容
标签: c struct initialization malloc constants