0

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?

8
  • 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. Commented Oct 19, 2018 at 13:41
  • You can't store a pointer to an int where an int is expected. Commented Oct 19, 2018 at 13:41
  • Is this code fragment supposed to be allocating space for the 2D array? Commented Oct 19, 2018 at 13:41
  • @dbush its supposed to store space for one entry of the array, would it be better to allocate all space at ones? Commented Oct 19, 2018 at 13:43
  • @Biswapriyo sry its supposed to be board_t Commented Oct 19, 2018 at 13:45

1 Answer 1

3

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.