I have created an array of structs and I am getting a BAD_ACCESS error. When I switch everything to dot notation it works fine, why is this?
Struct
typedef struct data{
int num;
}data;
Main
int main(void){
// This works
data data[4];
data[0].num = 10;
printf("Number is = %d\n", data[0].num);
// This does not work
data *data[4];
data[0]->num = 10;
printf("Number is = %d\n", data[0]->num);
// This does not work
data *data[4];
data[0]->num = 10;
printf("Number is = %d\n", data[0]->num);
Since data
is an array of four pointers, data[0]
is the first of those four pointers. But what does it point to? Since you haven't done something like data[0] = malloc(sizeof(struct data));
, it points to nothing in particular -- uninitialized garbage. It's not surprising that trying to write to what the pointer points to causes a bad access error.
Before you dereference a pointer, you need to make the pointer actually point to something.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.