Reputation: 75
I've a problem with my code. I have to input data into a struct for n times. To choose the cardinality of the struct during the declaration of the variables, I write: struct table T[DIM]; but.. DIM is a constant...so ... I would like to make somehow, dynamic the constant. I would do this, using a pointer. Then...:
const int DIM
int *p=&DIM
Next, I'm going to load the struct with data using a for. But before starting the for I want to ask what is the cardinality of the struct in this way:
printf("\nEnter the number of flights to manage");
scanf("%d", &*p)
Everything seems to work but while I run the insertion cycle, in the second or third cycle, this crash. Now I will enter the relevant code part:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <process.h>
struct table {
int cod;
char departure[20];
char arrival[20];
int tot_seats;
int seats_busy;
};
int main(int argc, char *argv[]){
const int DIM;
int *p=&DIM
struct table T[DIM];
int menu=0;
int menu1=0;
int I=0;
int TAB=0;
int flight;
int cont=0;
printf("---------------------------Airports------------------------\n\n");
while(menu!=3){
printf("\nWelcome to the software! Choose the most suitable function for your needs: \n \n");
printf("Do you run an airport or travel agency? Answer by typing the number associated with the response\n");
printf("1) Airports\n"); /*Apro il primo menù*/
printf("2) Travel agency\n");
printf("3) Exit\n");
scanf("%d", &menu);
printf("\n--------------------------------------------------------------------- \n \n");
switch(menu){
case 1: system("cls");
printf("\nYou have chosen the airport option\n-- You can now load the table --\n \n");
printf("\nEnter the number of flights to manage\n");
TAB=1;
for(I=0;I<DIM;I++){
printf("\n You are completing the line %d \n", I+1);
getchar();
printf("\nEnter the departure city:");
gets(&T[I].departure);
printf("\nEnter the city of arrival:");
gets(&T[I].arrival);
printf("\nEnter the flight code:");
scanf("%d", &T[I].cod);
printf("\nEnter the total number of flight seats:");
scanf("%d", &T[I].tot_seats);
}
printf("CODE -- DEPARTURE -- ARRIVAL-- TOT_SEATS\n");
for(I=0;I<DIM;I++){
printf("%d -- %s -- %s -- %d \n", T[I].cod, T[I].partenza,T[I].arrivo,T[I].tot_posti);
}
break;
Also eclipse tells me that in correspondence with:
gets(&T[I].departure);
and
gets(&T[I].arrival);
there is an error: passing argument 1 of 'gets' from incompatible pointer type [enabled by default].
How can I fix both errors? Thanks in advance!
Upvotes: 0
Views: 202
Reputation: 44
This is why malloc has been created :) You can allocate dynamically an array with the size, given as an input, like the number of flights in your example. if you have p flights you can create a table
T = (int) malloc(p*sizeof(int);
then you can iterate through your table from 0 to p. regards
Upvotes: 1