I am trying to understand why the following code compiles and runs fine. I would expect any assignment using data
inside f
not to compile with a gcc error assignment of member ‘i’ in read-only object
. Is there some kind of exception, because data.i
is allocated dynamically?
#include <stdio.h>
#include <stdlib.h>
struct a {
int *i;
};
void f(const struct a *data) {
data->i[0] = 55;
}
int main() {
struct a data;
data.i = malloc(2 * sizeof(int));
f(&data);
printf("%d\n", data.i[0]);
return 0;
}