Reputation: 27
I have this code-fragment out of my programm:
typedef struct board_t{
int x_pos;
int y_pos;
int size;
int counter;
int** field;
};
int func(struct board_t* b){
[...]
int i;
for(i=b->size; i>=1; i--){
int y;
for(y=b->size; y>=b->size; y--){
b->field[i][y] = (int*)malloc(sizeof(int)); //warning here
if(b->field[i][y] == NULL){
printf("Failed to save memory...");
return 1;
}
}
}
}
field is a 2-dimensional array from type double-pointer. Now I get a warning "assignment makes integer from pointer without cast". Could someone explain this to me and how to fix it?
Upvotes: 0
Views: 513
Reputation: 223927
This code isn't allocating space for the array correctly.
When you attempt to assign to b->field[i][y]
, there are two problems with this. First, this field has type int
, but you're attempting to assign a pointer to it. That's where the warning is coming from. Second, field
does not yet point anywhere, so field[i]
is dereferencing an unintialized pointer. You can't do that until you first assign something to field
.
What you need to do is allocate space for an array of int *
and assign it to field
(the first dimension), then for each array member allocate space for an array of int
and assign it to each member (the second dimension):
int i;
b->field = malloc(b->size * sizeof(*b->field));
if (!b->field) {
perror("malloc failed");
exit(1);
}
for (i=0; i<b->size; i++) {
b->field[i] = malloc(b->size * sizeof(**b->field));
if (!b->field[i]) {
perror("malloc failed");
exit(1);
}
}
Upvotes: 3