Reputation: 23
At first I'd like to say that despite experience with other programming lanugages, I'm new to C and I'm trying my best to understand all of its concepts. I know that dynamic allocation and especially 2d arrays inside structures aren't things that C is good at, but regardless of that I would like to understand how it functions.
First of all the reason why I'm trying to use a dynamic 2d array instead of two 1d arrays is because I'd like to benefit from the foo[x][y] syntax. Also array foo[x][y] should change it's size according to what's passed to function that allocates memory for the enitre struct.
My problem is that I cannot seem to correctly allocate enough memory for array inside a Bus
struct. I've been looking around web but I cannot seem to find a working example of such allocation and adapt it to my example. What I've tried so far was: declaring flexible array memeber inside struct and allocating it with 'make_structure' function, to later access it with macro.
Current example has the "pointer to a pointer" way of declaring dynamic 2d array. The program crashes when it's ran. Functions:
struct Bus *head;
struct Bus *current;
struct Bus *new;
struct Bus *make_structure(int r, int s);
void test() {
int i, NUM;
srand(time(NULL));
head = make_structure(ROW_SIZE, SEAT_AMOUNT);
current=head;
random_fill_structure(current);
current->next=NULL;
current=head;
show_structure();
}
struct Bus *make_structure(int r, int s) {
int i;
struct Bus* a;
a->seats = (int**)calloc(r,sizeof(int*));
for (i=0;i<r; i++) {
a->seats[i] = (int*)calloc(s,sizeof(int));
}
if(a==NULL)
{
puts("Error");
exit(1);
}
return(a);
}
struct Bus {
char name[20];
int **seats;
struct Bus *next;
};
The other two functions present in driver function random_fill_structure
and show_structure
don't do anything with the seats**
array so they shouldn't be the case of programme crashing.
Edit 1:
I've allocated memory for the struct in make_structure
function with this line of a=(struct Bus *)malloc(sizeof(struct Bus));
and the programme doesn't crash anymore. Though whenever I'd try to access it inside show_structure
like so:
for (i = 0; i < ROW_SIZE; i++) {
for (j = 0; j < SEAT_AMOUNT; j++) {
printf("[%d]", a->seats[i][j]);
}
}
The app will crash as it tries to print the first value of 2d array.
Edit 2: Function used to print the structure:
void show_structure() {
int i, j;
struct Bus *ptr = head;
while(ptr != NULL) {
printf("%s slots: ",ptr->name);
printf("\n");
ptr = ptr->next;
for (i = 0; i < ROW_SIZE; i++) {
for (j = 0; j < SEAT_AMOUNT; j++) {
printf("[%d]", ptr->seats[i][j]);
}
}
}
}
Upvotes: 0
Views: 126
Reputation: 14157
You shoul allocate memory for 'a' before accessing 'a->seats'.
struct Bus *a = malloc(sizeof *a);
Upvotes: 0