I am trying to create a function that takes in a array of structs as a parameter. This is part of my code so far:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdbool.h>
#define MAXREAD 256
#define MAXARR 64
struct block {
char free;
bool end;
};
void display(struct block *b){
char *p;
printf("|");
for(int i=0; i<MAXARR; i++){
p = &b[i].free;
//printf("%c ", *p);
printf("%c", (*p != '\0' ? '#':'-'));
//printf("%d", p);
if(b[i].end){
//printf("%d\n", i);
printf("|");
}
//printf("%c", blocks[i]->end ? "true":"false");
}
printf("\n");
}
int main(){
char input[MAXREAD];
struct block (*blocks)[MAXARR];
char cmd;
int number;
blocks = malloc(sizeof(struct block));
char *a;
//int *m;
for(int i=0; i<MAXARR; i++){
blocks[i]->free = '\0';
blocks[i]->end = malloc(sizeof(bool));
blocks[i]->end = false;
}
blocks[MAXARR-1]->end = true;
display(blocks);
while(strcmp(input, "q") != 0){
printf("How many blocks do you want to allocate/free?\n");
fgets(input, MAXREAD, stdin);
a = strchr(input, '\n');
*a = '\0';
sscanf(input, "%c %d",&cmd, &number);
if(strchr(input, 'q')){
break;
} else if(strchr(input, 'a')){
alloc(number, blocks);
} else if(strchr(input, 'f')){
dealloc(number, blocks);
}
display(blocks);
}
exit(0);
}
When I compile the program, this warning shows up:
warning: incompatible pointer types passing 'struct block (*)[64]' to parameter of type 'struct block *' [-Wincompatible-pointer-types] display(blocks);
I looked into these two posts and tried it out but the warning keeps showing up regardless:
Passing an array of structs in C
How to pass an array of struct using pointer in c/c++?
can someone please explain to me what is wrong with my program?
struct block (*blocks)[MAXARR];...hhmmmm - Sourav Ghoshblocksas an array of 64 pointers tostruct block. Then you usemallocto allocate a block of memory equal to the size of onestruct blockand assign this toblocks. This is wrong.blocksis already allocated to the stack and has the size of 64 pointers. You should instead allocate a block of memory for eachblock[i]inside the for loop. This is not your only problem though. - axxis