N
Noob
Hello,
Is it possible, in standard C89 and C99, to initialize a
struct whose fields are const with values only known at
run-time?
For example, consider:
struct toto { const int i; const float f; const void *p; };
Is it possible to portably implement:
struct toto *foo(int i, float f, void *p);
which allocates space for a "struct toto", initializes it
with i, f, p and returns the address of this struct?
The best I could come up with is:
#include <stdlib.h>
#include <string.h>
struct toto *foo(int i, float f, void *p)
{
struct toto s = { i, f, p };
struct toto *res = malloc(sizeof *res);
if (res != NULL) memcpy(res, &s, sizeof s);
return res;
}
which has several defects:
1) Apparently, C89 does not allow one to use elements "not computable
at load time" in an initialization list. However, it is allowed both
in C99 (right?) and in gnu89.
2) I'm not sure it is well-defined to memcpy stuff into some const
fields. Does it tickle the cranky UB gods?
Regards.
Is it possible, in standard C89 and C99, to initialize a
struct whose fields are const with values only known at
run-time?
For example, consider:
struct toto { const int i; const float f; const void *p; };
Is it possible to portably implement:
struct toto *foo(int i, float f, void *p);
which allocates space for a "struct toto", initializes it
with i, f, p and returns the address of this struct?
The best I could come up with is:
#include <stdlib.h>
#include <string.h>
struct toto *foo(int i, float f, void *p)
{
struct toto s = { i, f, p };
struct toto *res = malloc(sizeof *res);
if (res != NULL) memcpy(res, &s, sizeof s);
return res;
}
which has several defects:
1) Apparently, C89 does not allow one to use elements "not computable
at load time" in an initialization list. However, it is allowed both
in C99 (right?) and in gnu89.
2) I'm not sure it is well-defined to memcpy stuff into some const
fields. Does it tickle the cranky UB gods?
Regards.