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 deneme *mydeneme = malloc(sizeof(struct deneme));
return 0;
}
And this is the compiler’s error:
gereksiz.c:3:17: error: expected ':', ',', ';', '}' or '__attribute__' before '=' token
And, also this;
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;
}
And this is the compiler’s error:
gereksiz.c:10:5: error: assignment of read-only member 'a'
gereksiz.c:11:5: error: assignment of read-only member 'b'
And neither got compiled. Is there any way to initialize a const variable inside a struct when allocation memory with malloc?
You need to cast away the const to initialize the fields of a malloc’ed structure:
Alternately, you can create an initialized version of the struct and memcpy it:
You can make
deneme_initstatic and/or global if you do this a lot (so it only needs to be built once).Explanation of why this code is not undefined behaviour as suggested by some of the comments, using C11 standard references:
This code does not violate 6.7.3/6 because the space returned by
mallocis not "an object defined with a const-qualified type". The expressionmydeneme->ais not an object, it is an expression. Although it hasconst-qualified type, it denotes an object which was not defined with a const-qualified type (in fact, not defined with any type at all).The strict aliasing rule is never violated by writing into space allocated by
malloc, because the effective type (6.5/6) is updated by each write.(The strict aliasing rule can be violated by reading from space allocated by
mallochowever).In Chris’s code samples, the first one sets the effective type of the integer values to
int, and the second one sets the effective type toconst int, however in both cases going on to read those values through*mydenemeis correct because the strict-aliasing rule (6.5/7 bullet 2) permits reading an object through an expression which is equally or more qualified than the effective type of the object. Since the expressionmydeneme->ahas typeconst int, it can be used to read objects of effective typeintandconst int.