adding value to struct, adding goes wrong in C - c

I'm new to programming so I'm trying to write a small program were I can show car information but also add cars to my "library"
right now my out come for 1.Show cars looks like this:
ID BRAND PICS
bbb188 BMW 1 2 3
AAA-999 VOLVO 4 5 6
CCC-999 CITROEN 1 2 3
but after I add a new car the PICS does not show.
so if I would add AAA-111 VOLVO 1. this is the outcome:
bbb188 BMW 1 2 3
AAA-999 VOLVO 4 5 6
CCC-999 CITROEN 1 2 3
AAA-111 VOLVO -398253632 3 3
I just get random numbers for pics and always 3 values.
Could anyone help me with this, and please show me how to do it instead.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MAX 1000
#define IDSIZE 20
#define BRANDSIZE 50
#define PICSIZE 10
typedef struct{
char id[IDSIZE+1];
char brand[BRANDSIZE+1];
int *pic;
} Car;
void printCar(Car *pCar,int imagecount)
{
printf(" %s ",pCar->id);
printf(" %s ",pCar->brand);
for(int i=0; i<imagecount; i++){
printf(" %d",pCar->pic[i]);
}
printf("\n");
}
Car initCar(char itsId[],char itsBrand[],int *itsPic, int imagecount)
{
Car newCar;
strcpy(newCar.id, itsId);
strcpy(newCar.brand, itsBrand);
newCar.pic = itsPic;
return newCar;
}
void PrintList(Car aLista[],int imagecount, int carcount)
{
for(int i = 0; i<imagecount; i++)
printCar(&aLista[i],carcount);
}
void AddCar(Car aList[], int *pAt, Car theCar)
{
aList[(*pAt)++]=theCar;
}
Car NewCar(Car minapatienter[], int patientCount)
{
Car newCar;
gets(newCar.id);
printf("type in ID \n");
gets(newCar.id);
printf("type in brand\n");
gets(newCar.brand);
bool imageInputDone = false;
int imageCount=0;
while(imageInputDone == false)
{
printf("type in image reference \n");
int newImage;
scanf("%d",&newImage);
newCar.pic = &newImage;
imageCount++;
printf("vill du \n1.Add another image reference \n2.exit\n");
int input;
scanf("%d", &input);
printf("input: %i\n",input);
switch(input)
{
case 1:
printf("Adding one more image\n");
break;
case 2:
printf("Leaving loop\n");
imageInputDone = true;
break;
default:
while (input<1 || input<2)
;
printf("Input correct number\n");
break;
}
return newCar;
}
}
int main(void)
{
int carCount=0;
int imagecount=0;
Car myCar[MAX];
int input;
int test[3]={1,2,3};
int test2[3]={4,5,6};
myCar[0]= initCar("bbb188","BMW", test, 3);
myCar[1] = initCar("AAA-999","VOLVO", test2, 3);
myCar[2] = initCar("CCC-999", "CITROEN", test,3);
carCount=3;
imagecount=3;
do {
printf("1. Show cars \n2. Add car \n");
scanf("%d",&input);
switch(input)
{
case 1:
printf("ID BRAND PICS \n");
PrintList(myCar,carCount, imagecount);
break;
case 2:
AddCar(myCar,&carCount,NewCar(myCar,carCount));
printf("ID BRAND PICS \n");
PrintList(myCar,carCount, imagecount);
} //break;
} while (input < '1'|| input < '2');
return 0;
}

Your NewCar function have some problems. The newImage is in stack memory. When you do assignment newCar.pic = &newImage; the newCar.pic will point to undefined memory region because newImage was out of its scope. better way, we just use its value only, don't use address operator here. And one more thing, the newCar.pic is an pointer (array of int). So you need to allocate it before use. When you add more image item, you need to reallocate it. And initialize the pic to NULL pointer as well.
Here is my modification your NewCar function:
Car NewCar(Car minapatienter[], int patientCount)
{
Car newCar;
gets(newCar.id);
printf("type in ID \n");
gets(newCar.id);
printf("type in brand\n");
gets(newCar.brand);
newCar.pic = NULL;
bool imageInputDone = false;
int imageCount=0;
while(imageInputDone == false)
{
printf("type in image reference \n");
int newImage;
scanf("%d",&newImage);
// Rellocation
newCar.pic = realloc(newCar.pic, (imageCount+1)*sizeof(int));
newCar.pic[imageCount] = newImage;
imageCount++;
printf("vill du \n1.Add another image reference \n2.exit\n");
int input;
scanf("%d", &input);
printf("input: %i\n",input);
switch(input)
{
case 1:
printf("Adding one more image\n");
break;
case 2:
printf("Leaving loop\n");
imageInputDone = true;
break;
default:
while (input<1 || input<2)
;
printf("Input correct number\n");
break;
}
return newCar;
}
}

You get the same number of images printed for each car because you only have a global counter. You need a counter per image:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MAX 1000
#define IDSIZE 20
#define BRANDSIZE 50
#define PICSIZE 10
typedef struct Car
{
char id[IDSIZE+1];
char brand[BRANDSIZE+1];
int *pic;
int imagecount;
} Car;
With this change there is no need to pass a count for printing:
void printCar(Car *pCar)
{
printf(" %s ", pCar->id);
printf(" %s ", pCar->brand);
for(int i=0; i<pCar->imagecount; i++)
{
printf(" %d",pCar->pic[i]);
}
printf("\n");
}
The counter needs to be stored during initialization:
Car initCar(char itsId[], char itsBrand[], int *itsPic, int imagecount)
{
Car newCar;
strcpy(newCar.id, itsId);
strcpy(newCar.brand, itsBrand);
newCar.pic = itsPic;
newCar.imagecount = imagecount;
return newCar;
}
When you print your list, you mix up count of images and count of cars:
void PrintList(Car aLista[], int imagecount, int carcount)
{
for(int i = 0; i<imagecount; i++)
printCar(&aLista[i],carcount);
}
This must be:
void PrintList(Car aLista[], int carcount)
{
for (int i = 0; i < carcount; i++)
printCar(&aLista[i]);
}
Adding the car to your array is basically OK, but you might check if you reach MAX cars.
void AddCar(Car aList[], int *pAt, Car theCar)
{
aList[(*pAt)++]=theCar;
}
Now the biggest problem. This function hads issues with memory usage and weird loops.
Car NewCar(void)
{
Car newCar = {0}; // initialze with empty strings and NULL pointers.
// TODO: Replace gets with fgets!
// gets(newCar.id); // WHY read before you prompt??
printf("type in ID \n");
gets(newCar.id);
printf("type in brand\n");
gets(newCar.brand);
bool imageInputDone = false;
int imageCount=0;
while(imageInputDone == false)
{
printf("type in image reference \n");
int newImage;
scanf("%d",&newImage);
imageCount++;
int *newpics = realloc(newCar.pic, (imageCount) * sizeof(int));
newpics[imageCount-1] = newImage;
newCar.pic = newpics;
// TODO: Check for NULL
printf("vill du \n1.Add another image reference \n2.exit\n");
int input;
scanf("%d", &input);
printf("input: %i\n",input);
while (input < 1 || input > 2)
switch(input)
{
case 1:
printf("Adding one more image\n");
break;
case 2:
printf("Leaving loop\n");
imageInputDone = true;
break;
default:
printf("Input correct number\n");
break;
}
newCar.imagecount = imageCount;
return newCar;
}
}
And finally...
int main(void)
{
int carCount=0;
Car myCar[MAX];
int input;
int test[3] = {1,2,3};
int test2[3] = {4,5,6};
myCar[0] = initCar("bbb188", "BMW", test, 3);
myCar[1] = initCar("AAA-999", "VOLVO", test2, 3);
myCar[2] = initCar("CCC-999", "CITROEN", test, 3);
carCount=3;
do
{
printf("1. Show cars \n2. Add car \n");
scanf("%d", &input);
switch(input)
{
case 1:
printf("ID BRAND PICS \n");
PrintList(myCar, carCount);
break;
case 2:
AddCar(myCar, &carCount, NewCar());
printf("ID BRAND PICS \n");
PrintList(myCar, carCount);
} //break;
} while (input < 1 || input > 2); // compare as integers, not characters. Don't use < operator
return 0;
}
The code is not tested. Remaining errors are left for exercise. ;)

Related

Why does Dereferencing a Pointer Variable in my Helper Function causes my entire program to terminate?

My Helper Function, getInput() will read the data into the array list until end of input, where they will read in the Staff ID, total number of leave allowed and the number of days of leave taken so far. It is supposed to return the number of records read through the pointer variable n. However, when I try to dereference the pointer, the program will close and I am not sure why. Thank you in advance
My Code:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 80
typedef struct {
int id; /* staff identifier */
int totalLeave; /* the total number of days of leave allowed */
int leaveTaken; /* the number of days of leave taken so far */
}leaveRecord;
// Function Prototypes
void getInput(leaveRecord list[ ], int *n);
int mayTakeLeave(leaveRecord list[ ], int id, int leave, int n);
void printList(leaveRecord list[ ], int n);
int main(){
int choice, ID, LEAVE, leaveApproval;
int recordsRead = 0;
int *ptr = recordsRead;
leaveRecord list[SIZE];
do{
printf("Please Select one of the following Options:\n");
printf("1: getInput()\n");
printf("2: mayTakeLeave()\n");
printf("3: printList()\n");
printf("4: Quit!!\n");
scanf("%d", &choice);
switch(choice){
case 1:
getInput(list, recordsRead);
printf("Temp is %d", recordsRead);
break;
case 2:
printf("Please Enter the Staff ID:\n");
scanf("%d", &ID);
printf("Please Enter the Number of Days of Leave:\n");
scanf("%d", &LEAVE);
leaveApproval = mayTakeLeave(list,ID,LEAVE, ptr);
switch(leaveApproval){
case -1:
printf("Error!! Staff Member not found!");
break;
case 0:
printf("Leave is not approved");
break;
case 1:
printf("Leave is approved");
break;
}
break;
case 3:
break;
}
}while (choice < 3);
return 0;
}
void getInput(leaveRecord list[ ], int *n){
int option = 0, temp = 0;
int userInput;
while (option == 0){
printf("Please key in the Staff Identifier:\n");
scanf("%d", &list->id);
printf("Please key in the Total Number of Days allowed:\n");
scanf("%d", &list->totalLeave);
printf("Please key in the Number of Days of Leave taken:\n");
scanf("%d", &list->leaveTaken);
printf("Please Key in 1 if you like to stop adding Records:\n");
scanf("%d", &userInput);
if(userInput == 1){
break;
}
temp += 1;
}
// Why does dereferencing a Pointer Variable kill the entire program?
*n = temp;
}
int mayTakeLeave(leaveRecord list[ ], int id, int leave, int n){
int leaveUsed = (leave + list->leaveTaken);
for(int i = 0; i < n; i += 1){
if(list->id == id){
if((leaveUsed < list->totalLeave) || (leaveUsed == list->totalLeave)){
return 1;
}
else{
return 0;
}
}
else{
return -1;
}
}
}
void printList(leaveRecord list[ ], int n){
for(int i = 0; i < n; i += 1){
printf(list);
}
}
void getInput(leaveRecord list[ ], int *n);
Here, In getInput function n is an integer type pointer variable which wants address of integer variable.
But here, getInput(list, recordsRead) you are just sending value of records read.
You have to send address of recordsRead.
getInput(list, &recordsRead)
Also in function printList you are using wrong syntax.
printf(list);
Do this :
printf("%d",list[i]);
or
printf("%d",*(list+i));

Nested structures and dynamic memory allocation

I am currently learning C and trying to create an app that allows students to input their name, address, student id and any subject id they have while at university (yes this is a task part of foundations of tech course). Basically the following code tries to create an array of students (that is unlimited in size) by using dynamic allocating memory. Further a student can have unlimited amounts of subjects (that is nested within the student subject and is dynamically allocated)
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main()
{
typedef struct {
char subjectID[10];
char subjectName[10];
float grades;
}subject;
typedef struct {
char name[10];
int id;
struct subject *enrol;
char address[100];
int status;
int totalSubject;
}student; // This structure is to act like an unlimited list of students
int option=0, q=0, j=0, k=0, p=0, delete=0, position=0;
int count=0; // keeps the count of numbers added
student * studentAddress;
studentAddress = NULL; //Init structure
studentAddress->enrol = NULL; // Init nested structure
int flag = 0; //variable to indicate whether the number to delete is found or not
while (1) // Life cycle of the app
{
printf("1 - Add new student\n");
printf("2 - Display all students\n");
printf("3 - Delete student by id \n");
printf("4 - Delete student by name \n");
printf("5 - Quit\n");
scanf("%d",&option);
switch (option)
{
case 1: studentAddress = realloc(studentAddress, sizeof(student)*(count+1)); //using realloc memory is requested for the new number
printf("Enter your name\n");
fflush(stdin);
gets(studentAddress[count].name);
fflush(stdin);
printf("Enter your id\n");
scanf("%d", &studentAddress[count].id);
printf("Enter your address\n");
fflush(stdin);
gets(studentAddress[count].address);
fflush(stdin);
int subjectCounter = 0;
subjectCounter = 0;
char subjectContinue[10];
for (p = 0; p < subjectCounter; p++)
{
studentAddress[count].enrol = (struct subject *)realloc(studentAddress[count].enrol, (sizeof(subject)*(subjectCounter+1)));
// studentAddress[count].enrol[subjectCounter] = (struct subject *)realloc(sizeof(subject)*(subjectCounter+1));
// Above is teacher paste
printf("What is the id of your subject %d\n", (subjectCounter+1));
fflush(stdin);
gets(studentAddress[count].enrol[subjectCounter].subjectID);
fflush(stdin);
printf("Would you like to add another subject id\n");
fflush(stdin);
gets(subjectContinue);
fflush(stdin);
if (strcmp(subjectContinue, "Y") == 0)
{
subjectCounter++;
}
studentAddress[count].totalSubject = subjectCounter;
}
count++;
printf("\n");
break;
case 2:
for (j=0; j<count; j++)
{
if(studentAddress[j].status != 0)
printf("%s\n %d\n %s\n", studentAddress[j].name, studentAddress[j].id, studentAddress[j].address);
for (q = 0; q < studentAddress[count].totalSubject; q++)
{
printf("%s", studentAddress[j].enrol[q].subjectID);
}
}
printf("\n");
break;
case 3: k=count;
flag=0;
printf("Type the id of the person record you want to delete\n");
scanf("%d", &delete);
for (j=0; j < count; j++)
{
if (delete == studentAddress[j].id)
{
strcpy(studentAddress[j].name, " ");
strcpy(studentAddress[j].address, " ");
studentAddress[j].id = 0;
studentAddress[j].status = 0;
flag = 1;
}
}
if(flag==0)
printf("id not in the list ...\n");
else
printf("Deletion successful ...\n");
printf("\n");
break;
case 4:
flag=0;
char deletChar[100];
printf("Type the name of the person record you want to delete\n");
fflush(stdin);
gets(deletChar);
fflush(stdin);
for (j=0; j < count; j++)
{
if (strcmp(deletChar, studentAddress[j].name)==0)
{
flag = 1;
strcpy(studentAddress[j].name, " ");
strcpy(studentAddress[j].address, " ");
studentAddress[j].id = 0;
studentAddress[j].status = 0;
flag = 1;
}
}
if(flag==0)
printf("name not in the list ...\n");
else
printf("Deletion successful ...\n");
printf("\n");
break;
return 0;
case 5:
return 0;
}
}
return 0;
}
I try running this code and get the error on line 68 and similar on line 95
subscript of pointer to incomplete type 'struct subject'
gets(studentAddress[count].enrol[subjectCounter].subjectID);
plus I get this note (from the compiler) below the error
forward declaration of 'struct subject' struct subject *enrol;
My tutor and lecture have both tried helping me, but they have had no success. They are like most of my code looks correct, but it will not work. Sorry I am new to stack overflow so if you want me to add more information please let me know.
The easiest way to solve this is to create a function.
struct student* allocate_student() {
struct subject* new_subject = allocate_subject();
struct student* new_struct = malloc(sizeof(struct student));
// initialize all fields, which will eventually include
new_struct->enrol = new_subject;
return new_struct;
}
This code fails to check for any error conditions. You should add that. In addition, allocate_subject() is also not defined. Considering the offered example, odds are good you can figure out how to write allocate_subject().
If you add in parameters, allocate_student() might be a bad method name. With enough parameters to construct any student, you might want to call it construct_student(...)

Read values into an array fails

I want to use a function to scanf up to 10 values for an array with the size 10, and also keep track of the number of values that are in the array because I'll need it later for solving some maths about the array, (max value, min value, etc.).
#include <stdio.h>
int enter(int MeasurmentData[], int nrOfmeasurments)
{
for(int i=0;i<10;++i)
{
int MeasurmentData[10];
scanf("%d",&MeasurmentData[i]);
int nrOfmeasurments = 0;
nrOfmeasurments ++;
return nrOfmeasurments;
}
int main()
{
int MeasurmentData[10];
int nrOfmeasurments;
char menuoption;
while (1)
{
printf("Measurment tool 2.0\n");
printf("v (View)\n");
printf("e (Enter)\n");
printf("c (Compute)\n");
printf("r (Reset)\n");
printf("q (Quit)\n");
printf("enter your option:\n");
scanf(" %c", &menuoption);
if (menuoption =='e') \\ enter values
{
int MeasurmentData[10];
int nrOfmeasurments;
enter(MeasurmentData, nrOfmeasurments);
}
else if(menuoption == 'v') \\\ view values
{
//printf("%d", MeasurmentData[]);
}
else if(menuoption == 'c')
{
}
if(menuoption == 'q')
{
printf("Exiting Measurment tool 2.0\n");
return 0;
}
}
}
When I run the program it should print Measurment tool 2.0, after the the user has the choice of inputting e(enter) which will scan in up to 10 values into an array, if the user clicks q(quit) while in the enter option already he will be returned to the main menu where he can do whatever.
V(view) prints out the array for the user so that he can view what elements are inside.
C(compute) uses the elements inside and the nr of elements to calculate the highest value element, lowest.
There are some errors in your code. Ill try to explain. You have over declared your variables too many times. And since you have a fixed loop you don't need to count the measurements you will always read 10 measurements.
Below are the code with some modifications. Feel free to ask anything about it.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXIMUM_MEASURMENT 10
int enter(int MeasurmentData[])
{
char input[100];
int nrMeasurement = 0;
// reseting Measurment data
for(int i=0;i<MAXIMUM_MEASURMENT;++i) MeasurmentData[i] = 0;
for(int i=0;i<MAXIMUM_MEASURMENT;++i)
{
scanf("%99s", input);
if(strcmp(input, "q") == 0) {
break;
}
MeasurmentData[i] = (int) strtol(input, (char **)NULL, 10);
nrMeasurement++;
}
return nrMeasurement;
}
void showMeasurments(int* MeasurmentData, int length) {
int i = 0;
printf(" ======== Measurment ======== \n");
for(i = 0; i < length; i++) {
printf("%d ", MeasurmentData[i]);
}
printf("\n");
}
int main()
{
int MeasurmentData[MAXIMUM_MEASURMENT];
int nrOfmeasurments;
char menuoption;
while (1)
{
printf("Measurment tool 2.0\n" "v (View)\n" "e (Enter)\n" "c (Compute)\n" "r (Reset)\n" "q (Quit)\n enter your option:\n");
scanf(" %c", &menuoption);
if (menuoption =='e') // enter values
{
enter(MeasurmentData);
}
else if(menuoption == 'v') // view values
{
// show
showMeasurments(MeasurmentData, MAXIMUM_MEASURMENT);
}
else if(menuoption == 'c')
{
}
if(menuoption == 'q')
{
printf("Exiting Measurment tool 2.0\n");
break;
}
}
return 0;
}
Edit: i have updated the code. So i have read the comments of your question and there you have explained a little better what you are trying to accomplish. So since you have the requirement to press 'q' to stop reading values. I have to read all measurments as string and convert to integer if it is not the character q.
Edit 2: Thanks to #user3629249 to point out some of the flaws from the code ill update with his suggestions.

C seg fault - where/what?

I have this program that is supposed to handle assigning seats to passengers.
I cannot figure out what is causing my seg fault. I am using an array of structs and that may be where the problem is coming from.
I think its probably a problem with dereferencing some struct members, but I can't find where.
Here is my code:
struct seat
{
// Max Name of 32 chars
char name[32];
// Seat Number
int sNum;
// Seat taken = 1, open = 0
int taken;
};
// Function headers
void seat(struct seat plane[][10]);
void mani(struct seat plane[][10]);
void pass(int seat, char name[], int class);
int main()
{
// My airline plane is 6 seats per row, 10 rows
// Row 1/2 are First Class
// Row 3/4 are Business Class
// Init counter variables to keep track of the number
// of First Class/Business seats already taken
// also the user input var
int input, ticketin, class1 = 0, class2 = 0, class3=0, sNum, i;
char namein[32];
// Vars for pass function
char passname[32];
int passclass;
int passseat;
// Init a 2d array 6 colums 10 rows
struct seat plane[6][10];
for (i=0; i<sizeof(plane); i++)
{
plane[i]->sNum = i+1;
plane[i]->taken = 0;
}
// Begin user input loop
// Menu with 3 options:
// Display the seating chart, indicating taken seats
// Display the manifest
// Display a boarding pass - seat number, name, class
do
{
do
{
// Prompt user for ticket selection
printf("Please type 1 for \"First Class\"\n");
printf("Please type 2 for \"Business Class\"\n");
printf("Please type 3 for \"Economy Class\"\n");
scanf(" %d", &ticketin);
// Check for valid input
if (ticketin == 1)
{
// Check to make sure first class is not full
if (class1 < 12)
{
class1 += 1;
printf("First class is open!\n");
} else {
printf("First class is full, please choose another class\n");
}
} else if (ticketin == 2)
{
// Check to make sure business class is not full
if (class2 < 12)
{
class2 += 1;
printf("Business class is open!\n");
} else {
printf("Business class is full, please choose another class\n");
if (class1 < 12)
{
printf("Upgrade to First Class by entering 1");
}
}
} else if (ticketin == 3)
{
// Check to make sure business class is not full
if (class3 < 12)
{
class3 += 1;
printf("Economy class is open!\n");
} else
{
printf("Economy class is full, please choose another class\n");
if (class1 < 12)
{
printf("Upgrade to First Class by entering 1");
}
if (class2 < 12)
{
printf("Upgrade to Business Class by entering 2");
}
}
} else
{
ticketin = 4;
}
// Prompt the user for their name
printf("Please input your name:\n");
scanf(" %s", namein);
} while (ticketin == 4);
// Handle loading the new passenger into plane array
switch (ticketin)
{
case 1:
for (i=0; i<12; i)
{
if (plane[i]->taken == 0)
{
plane[i]->taken = 1;
strcpy(plane[i]->name, namein);
sNum = plane[i]->sNum;
} else
{
i++;
}
}
case 2:
for (i=12; i<24; i)
{
if (plane[i]->taken == 0)
{
plane[i]->taken = 1;
strcpy(plane[i]->name, namein);
sNum = plane[i]->sNum;
} else
{
i++;
}
}
case 3:
for (i=24; i<60; i)
{
if (plane[i]->taken == 0)
{
plane[i]->taken = 1;
strcpy(plane[i]->name, namein);
sNum = plane[i]->sNum;
} else
{
i++;
}
}
}
printf("Menu Options: \n");
printf("(1) Display the seating chart\n");
printf("(2) Display the passenger manifest\n");
printf("(3) Display a boarding pass\n");
printf("(4) Quit\n");
// Prompt user for their selection
printf("Please enter your menu selection:\n");
scanf(" %d", &input);
// Switch case handling function calls
switch (input)
{
case 1:
seat(plane);
break;
case 2:
mani(plane);
break;
case 3:
printf("Please input a seat number\n");
scanf(" %d", &passseat);
if (passseat < 12)
{
passclass = 1;
} else if (passseat < 24)
{
passclass = 2;
} else
{
passclass = 3;
}
pass(passseat, plane[passseat-1]->name, passclass);
break;
default:
printf("invalid menu option or quitting\n");
break;
}
} while (input != 4);
}
// Display seating chart function
void seat(struct seat plane[][10])
{
int i, sNum;
for (i=0; i<sizeof(plane); i++)
{
if (plane[i]->taken == 1)
{
printf("Seat %d is taken\n", i++);
} else
{
printf("Seat %d is not taken\n", i++);
}
}
}
// Display Manifest function
void mani(struct seat plane[][10])
{
int i;
for (i=0; i<sizeof(plane); i++)
{
if (plane[i]->taken == 1)
{
printf("Passenger %s in seat %d\n", plane[i]->name, i++);
}
}
}
// Display boarding pass function
void pass(int seat, char name[], int class)
{
printf("Boarding pass for %s\n", name);
printf("Seat Number: %d\n", seat);
switch (class)
{
case 1:
printf("First Class");
break;
case 2:
printf("Business Class");
break;
case 3:
printf("Economy Class");
break;
}
}
There are probably other errors, but this is the most obvious one:
for (i=0; i<sizeof(plane); i++)
{
plane[i]->sNum = i+1;
plane[i]->taken = 0;
}
sizeof(plane) is the number of bytes in the plane array. This is 10 * 6 * sizeof(struct seat), so you're writing way outside the array. If you want to know the number of elements in an array, you have to divide the size of the array by the size of an array element:
for (i=0; i<sizeof(plane)/sizeof(*plane); i++)
{
plane[i]->sNum = i+1;
plane[i]->taken = 0;
}
But your code is only initializing the first element in each row of the array.
Since it's a 2-dimensional array, you need nested loops. And you should use normal member access with . rather than pointer indirection.
for (i=0; i<sizeof(plane)/sizeof(plane[0]); i++)
{
for (int j = 0; j < sizeof(plane[i])/sizeof(plane[i][0]); j++)
{
plane[i][j].sNum = i+1;
plane[i][j].taken = 0;
}
}
You could simplify all the sizeof stuff by defining macros:
#define ROWS 6
#define COLS 10
and then using these macros in the array declaration and the for loop limits.
Similar changes need to be made in other code that loops over the plane array.

Can't initialize my array counter in C despite trying everything

I've been working on this school assignment which creates a restaurant menu, and I have an array to store everything that a person orders. The array that stores the orders ordered is array OrderedItems [30]. This array is basically a counter. When a person orders order number 1 as an example OrderItems[1] increases by 1.
I've tried to initialize by using OrderedItems [30] = {0}, and using a for loop to initialize every spot individually, However, that didn't work. Please help me initialize this array. I've also tried memset(OrderedItems, 0, 30); and this didn't work too so I really have no clue what to do.
I also want to add that I've tried to globally declare the OrderedItems array since I've heard that all global declarations are automatically initialized to 0, but that also didn't work.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <windows.h>
FILE *fPointer1; //for food//
FILE *fPointer2; //for invoice//
int count;
char name[50];
float price;
void FunctionToPrintFoodItems (void)
{
fPointer1 = fopen ("Food.txt", "a+");
float price;
printf("ITEMCODE\tDESCIPTION\tPRICE (RM)\n");
while (!feof (fPointer1))
{
fscanf(fPointer1, "%d %s %f", &count, name, &price);
printf("%d\t\t%s\t\t%.2f\n", count, name, price);
}
fclose (fPointer1);
}
void clrscr()
{
system("#cls||clear"); //might not need. Will delete it not needed//
}
void debug (void)
{
printf("THIS IS PRINTED");
}
#define clear clrscr ();
#define printfood FunctionToPrintFoodItems();
#define de debug();
int main ()
{
fPointer1 = fopen("Food.txt", "w");
fprintf(fPointer1, "1 BigM 10.40\n");
fprintf(fPointer1, "2 Cheeseburger 9.45");
fclose (fPointer1);
int i;
int MainMenuCode;
int additems = 0;
int orderitems;
int item;
int ordered;
int OrderedItems[30] = {0};
memset(OrderedItems, 0, 30);
for (i=0 ; i < 30 ; i++)
{
OrderedItems[i] = NULL;
printf("%d: %d\n", i, OrderedItems);
}
do
{
printf("WELCOME TO RESTOURANT MAC C - Main Menu\n\n");
printf("[1] Add new food items\n\n");
printf("[2] Take order\n\n");
printf("Enter ITEM CODE (0 to Quit) : ");
scanf("%d", &MainMenuCode);
if (MainMenuCode == 1)
{
clear;
additems = 1;
printf("WELCOME TO RESTAURANT MAC C - Add Menu\n\n");
printfood;
printf("\n");
while ( additems == 1 )
{
printf("Enter description (0 to Main Menu) : ");
scanf("%s", name);
if (strcmp (name, "0") == 0)
{
additems = 0;
clear;
break;
}
printf("Enter price (RM) : ");
scanf("%f", &price);
count ++;
fPointer1 = fopen ("Food.txt", "a");
printf("\n%d\t\t%s\t\t%.2f\n\n", count, name, price);
fprintf(fPointer1, "\n%d %s %.2f", count, name, price);
fclose (fPointer1);
}
}
else if (MainMenuCode == 2)
{
clear;
orderitems = 1;
printf("WELCOME TO RESTAURANT MAC C- Take Order\n\n");
printfood;
while (orderitems == 1)
{
fPointer1 = fopen ("Food.txt", "a+");
printf("Enter ITEM CODE (0 to Quit, 100 for Main Menu) : ");
scanf("%d", &item);
if (item == 100) break;
else if (item == 0) //final approach//
{
fPointer2 = fopen ("Invoice.txt", "a+");
de;
fclose (fPointer2);
return 0;
}
else if (item == 900)
{
for (i=0 ; i < 30 ; i++)
printf("%d: %d\n", i, OrderedItems);
}
else if (item > count || item < 1)
{
printf("\n\nITEM CODE not available. Try again\n\n");
}
else
{
OrderedItems[item]++;
printf("%d %d", item, OrderedItems);
}
fclose (fPointer1);
}
}
else printf("Please enter a valid Menu Code\n");
} while (MainMenuCode != 0);
return 0;
}
- printf("%d: %d\n", i, OrderedItems);
+ printf("%d: %d\n", i, OrderedItems[i]);
OrderedItems is an address of the array's first element.
OrderedItems[0] is a value of the array's first element.
OrderedItems[i] is a value of the array's i-th element.
The call to memset should specify how many bytes to set. You need to tell it the size of the type to initialise.
memset(OrderedItems, 0, 30 * sizeof(int))

Resources