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;
}
In the below code,
constindicates whatdatapoints to is not to be modified.data->i[0] = 55;does not modify the pointerdata->i. Instead that line of code modifies the memory pointed to bydata->i. This is allowed as pointer.iisint *and notconst int *.