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
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:
void*
variable initialized with a malloc()
call. struct deneme
and initialize it in some way that const
qualifier does not complain (that is, in the declaration-line itself). memcpy()
to copy the bits of the struct deneme
object to the void*
object. 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;
}