0
votes

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?

1
b->field[i][y] is an integer. You try to assign a int* to it. This code overall doesn't make sense, you should allocate all memory at once with a single malloc call. - Lundin
You can't store a pointer to an int where an int is expected. - coredump
Is this code fragment supposed to be allocating space for the 2D array? - dbush
@dbush its supposed to store space for one entry of the array, would it be better to allocate all space at ones? - Feliboy
@Biswapriyo sry its supposed to be board_t - Feliboy

1 Answers

3
votes

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);
    }
}