Unable to read structures properly from binary - c

So my program creates an 2d-dynamic array of structures, reads these structures from a binary file, changes the information in the structures and writes them in the same file. The problem is, that it does not read the information from the file properly. For example, I expect the info from ptr[0][0].Flat_IDto be 101. But on the console it prints a random number, say10948144, and this jeopardizes my entire program. I tried to change the way it reads, but to no effect.
Here is my main():
#include "Header.h"
int main()
{
while(1)
{
printf("Hello world!\n");
unsigned int floors=0, flats_per_floor=0;
S_Apartament Flats;
char FileName[50];
printf("0. Exit program.\n");
printf("1. Enter a file name.\n");
printf("Please, choose a command.\n");
unsigned short choice;
scanf("%hu", &choice);
if(choice == 0)
{
break;
}
else
{
printf("Enter file name in the following format 'Name.bin' :");
scanf("%s", FileName);
}
S_Apartament **ptr = memalloc(floors, flats_per_floor, Flats, FileName);
printf("%u",ptr[0][0].Flat_ID);
while(1)
{
choice = menu();
if(choice==0)
{
break;
}
switch(choice)
{
case 1:
enterNewResidents(ptr, floors, flats_per_floor);
break;
case 2:
calculateTax(ptr, floors, flats_per_floor);
break;
case 3:
Elevator(ptr, floors, flats_per_floor);
break;
case 4:
emptyApartment(ptr, floors, flats_per_floor);
break;
default:
printf("Invalid command\n");
break;
}
writeInfo(ptr,floors,flats_per_floor, FileName);
free(ptr);
}
}
printf("Program exited successfully. Have a nice day");
return 0;
}
My header file:
#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
unsigned int Flat_ID;
unsigned short count_Rooms;
unsigned short count_Adults;
unsigned short count_Children;
char Family_Surname[20];
char Date[10];
float rent;
}S_Apartament;
unsigned short menu();
S_Apartament** memalloc(unsigned int floors, unsigned int flats_per_floor, S_Apartament Apartment, char FileName[50]);
void enterNewResidents(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor);
void calculateTax(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor);
void emptyApartment(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor);
void Elevator(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor);
void writeInfo(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor, char FileName[50]);
#endif // HEADER_H_INCLUDED
And my source file:
#include "Header.h"
unsigned short menu()
{
unsigned short choice=0;
printf("Welcome, to the smart House manager program! Here is a list of the available commands.\n");
printf("1. Enter new residents.\n");
printf("2. Calculate month tax.\n");
printf("3. Set elevator\n");
printf("4. Empty an apartment\n");
printf("0. Exit the program\n");
printf("Please choose a command:\n");
scanf("%hu",&choice);
return choice;
}
S_Apartament** memalloc(unsigned int floors, unsigned int flats_per_floor, S_Apartament Apartment, char FileName[50])
{
FILE *f;
f = fopen(FileName,"rb");
if(f==NULL)
{
printf("Error opening file, or no such file.");
fclose(f);
exit(1);
}
fread(&floors,sizeof(unsigned),1,f);
fread(&flats_per_floor,sizeof(unsigned),1,f);
fclose(f);
S_Apartament **arr = (S_Apartament **)malloc(sizeof(S_Apartament*) * floors);
for (int i = 0; i < floors; i++)
{
arr[i] = (S_Apartament *)malloc(sizeof(S_Apartament)*flats_per_floor);
printf("Here");
}
for(int i = 0; i < floors; i++)
{
for(int j = 0; j < flats_per_floor; j++)
{
fread(&Apartment,sizeof(S_Apartament),1,f);
arr[i][j]=Apartment;
}
}
fclose(f);
return arr;
}
void enterNewResidents(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor)
{
unsigned short a = 0, b = 0;
printf("Enter the floor, where you wish to accommodate the new residents.\n");
scanf("%hu", &a);
printf("Good, now the flat.\n");
scanf("%hu", &b);
if((a > floors) || (b > flats_per_floor))
{
printf("Invalid coordinates.");
}
if(ptr[a-1][b-1].count_Adults==0)
{
printf("The apartment is free to use. Enter the following data:\n");
printf("Enter the number of adults\n");
scanf("%hu", &(ptr[a-1][b-1].count_Adults));
printf("Enter the number of children\n");
scanf("%hu", &(ptr[a-1][b-1].count_Children));
printf("Enter the name of the Family\n");
scanf("%s", ptr[a-1][b-1].Family_Surname);
printf("Date of entry:\n");
scanf("%s", ptr[a-1][b-1].Date);
printf("Enter the rent\n");
scanf("%f", &(ptr[a-1][b-1].rent));
}
else
{
printf("The apartment is occupied. Please, choose another one.\n");
}
}
void calculateTax(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor)
{
int Tax = 0;
for(int i=0; i<floors; i++)
{
for(int j=0; i<flats_per_floor; j++)
{
if( (i==0) || (i==1) )
{
Tax = Tax + (3*ptr[i][j].count_Adults) + (1*ptr[i][j].count_Children);
}
else
{
Tax = Tax + (5*ptr[i][j].count_Adults) + (3*ptr[i][j].count_Children);
}
}
}
printf("Tax is: %d \n", Tax);
}
void Elevator(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor)
{
unsigned short Elevator_location = 1;
unsigned number_of_residents = 0;
unsigned max_amount = 0;
for(int i = 1; i < floors - 1; i++)
{
for(int j = 0; j<flats_per_floor; j++)
{
number_of_residents = number_of_residents + ptr[i][j].count_Adults + ptr[i][j].count_Children + ptr[i-1][j].count_Adults + ptr[i-1][j].count_Children + ptr[i+1][j].count_Adults + ptr[i+1][j].count_Children;
}
if(number_of_residents >= max_amount)
{
max_amount = number_of_residents;
number_of_residents = 0;
Elevator_location = i + 1;
}
else
{
number_of_residents = 0;
}
}
printf("The elevator's default floor is to be set to ");
if(Elevator_location == 2)
{
printf("%hu nd floor.\n", Elevator_location);
}
else if(Elevator_location == 3)
{
printf("%hu rd floor.\n", Elevator_location);
}
else
{
printf("%hu th floor.\n", Elevator_location);
}
}
void emptyApartment(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor)
{
unsigned short Entered_number = 0;
int i = 0, j = 0;
printf("Enter the number of the apartment you wish to empty:\n");
scanf("%hu", &Entered_number);
for(i=0; i<floors; i++)
{
for(j=0; j<flats_per_floor; j++)
{
if(Entered_number == ptr[i][j].Flat_ID)
{
ptr[i][j].count_Adults = 0;
ptr[i][j].count_Children = 0;
ptr[i][j].Family_Surname[0] = '\0';
ptr[i][j].rent = 0.00;
printf("Apartment is empty");
break;
}
}
if(Entered_number == ptr[i][j].Flat_ID)
{
printf("TEST");
break;
}
else if(i == (floors - 1))
{
printf("No such apartment");
}
}
}
void writeInfo(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor, char FileName[50])
{
FILE *fp;
fp = fopen(FileName,"wb");
if(fp==NULL)
{
printf("Error opening file");
fclose(fp);
exit(2);
}
fwrite(&floors,sizeof(unsigned),1,fp);
fwrite(&flats_per_floor,sizeof(unsigned),1,fp);
for(int i = 0; i < floors; i++)
{
for(int j = 0; j < flats_per_floor; j++)
{
fwrite(&ptr[i][j],sizeof(S_Apartament),1,fp);
}
}
fclose(fp);
}
I can think of no other way to fix this. Any help would be appretiated. Sorry for the huge amount of code.

In your memalloc and these lines you close the file
fread(&floors,sizeof(unsigned),1,f);
fread(&flats_per_floor,sizeof(unsigned),1,f);
fclose(f);
but later in your loop you try to read from it, and a few lines after this you close it again
for(int j = 0; j < flats_per_floor; j++)
{
fread(&Apartment,sizeof(S_Apartament),1,f);
arr[i][j]=Apartment;
}
Try removing the first fclose call.

Related

Array passed as parameter not accessible outside of user defined function

This code is to convert a inputted decimal number to binary, hex, and octal without format specifiers. It also is supposed to print the results to a text file. Every works fine except the 3 char arrays storing hex, oct, and binary are not accessible outside of the function that converted them.
#include <stdio.h>
#include <time.h>
char *getDateAndTime();
int getInteger();
int atoi(const char *str);
void decimalToBinary(int decValue, char binString[]);
void decimalToHex(int decValue, char hexString[]);
void decimalToOct(int decValue, char octString[]);
int saveFile(char name[], char *getDateAndTime(), int decValue, char octString[], char hexString[], char binString[]);
int main()
{
char binString[32];
char octString[32];
char hexString[32];
char dateTime[32];
char name[32];
int decValue = 0;
int saveSuccess = 0;
printf("Enter your name: ");
fgets(name, sizeof(name), stdin);
decValue = getInteger();
if (decValue != 'x'){
decimalToHex(decValue, hexString);
decimalToOct(decValue, octString);
decimalToBinary(decValue, binString);
saveFile(name, getDateAndTime, decValue, octString, hexString, binString);
}
printf("\nGoodbye!");
return 0;
}
char *getDateAndTime()
{
time_t t;
time(&t);
return ctime(&t);
}
int getInteger()
{
char number[9];
int num;
int status = 1;
do {
printf("Enter an Integer [1-1,000,000] or type x to exit: ");
fgets(number, sizeof(number), stdin);
if (number[0] == 'x')
{
status = 0;
}
else
{
num = atoi(number);
if (num < 1 || num > 1000000)
{
printf("Error: %d is out of range\n", num);
}
else
{
status = 0;
return num;
}
}
} while (status);
}
void decimalToBinary(int decValue, char binString[])
{
int quotient;
int i = 1;
int j;
quotient = decValue;
while(quotient!=0){
binString[i++]= quotient % 2;
quotient = quotient / 2;
}
printf("Decimal: %d\nBinary: ",decValue);
for(j = i -1 ;j> 0;j--)
printf("%d",binString[j]);
printf("\n");
}
void decimalToHex(int decValue, char hexString[]){
long int remainder,quotient;
int i=1,j,temp;
quotient = decValue;
while(quotient!=0){
temp = quotient % 16;
if( temp < 10)
temp =temp + 48;
else
temp = temp + 55;
hexString[i++]= temp;
quotient = quotient / 16;
}
printf("Hexadeciaml: ");
for(j = i -1 ; j> 0; j--)
printf("%c",hexString[j]);
}
void decimalToOct(int decValue, char octString[])
{
int quotient;
int i = 1;
int j;
quotient = decValue;
while(quotient!=0){
octString[i++]= quotient % 8;
quotient = quotient / 8;
}
printf("\nOctal: ");
for(j = i -1 ;j> 0;j--)
printf("%d",octString[j]);
printf("\n");
}
int saveFile(char name[], char* getDateAndTime(), int decValue, char octString[], char hexString[], char binString[])
{
char choice;
int status = 1;
printf("Save to a file? (y/n): ");
scanf(" %c", &choice);
while (status){
if (choice == 'y'){
FILE *ptr_file;
ptr_file =fopen("G01303907_HW3.txt", "w");
if (!ptr_file){
return 1;
}
int results = fprintf(ptr_file,"Name: %s\nDate: %s\nDecimal Value:%d\nHexadecimal String: %s\nOctal String: %s\nBinary String: %s\n",name, getDateAndTime(), decValue, hexString, octString, binString);
if (results == EOF) {
printf("Error: ");
}
fclose(ptr_file);
status = 0;
return 0;
}
else if (choice == 'n')
{
status = 0;
return -1;
}
else{
printf("Error: illegal value\nSave to a file? (y/n): ");
scanf("%s", &choice);
}
}
}
terminal
Enter an Integer [1-1,000,000] or type x to exit: 23
Hexadeciaml: 17
Octal: 27
Decimal: 23
Binary: 10111
Save to a file? (y/n): y
Goodbye!
Text Document
Name: Mason
Date: Mon Oct 3 23:38:59 2022
Decimal Value:23
Hexadecimal String:
Octal String:
Binary String:

Can anyone help me identify the error in my last function?

i have written this program (its not finished, there are more functions to be added) however, I want to know why my withinBudget function is sometimes producing correct results and other times producing inaccurate results. The withinBudget works out whether or not the customer has sufficient balance or not. if it returns true it prints purchase has been successful or prints insufficient balance.
#include <stdio.h>
int isItemExist(char itemPrefixes[], char itemPrefix);
void displayMenu(char itemPrefixes[], int itemPrices[], int n);
int withinBudget(int budget, char itemPurchased, char itemPrefixes[], int itemPrices[]);
int n;
int main() {
char itemPrefixes[5];
int itemPrices[5];
int budget = 0;
char itemPurchased;
printf("***ItemPrefixes***");
printf("\nA: Apple\n");
printf("O: Orange\n");
printf("M: Mango\n");
printf("P: Pear\n");
printf("G: Grapes\n");
printf("\n***ShopKeeperPanel***");
printf("\nHow many fruit items do you want to add to the shop?: ");
scanf_s("%d", &n);
int chosenFruitItem = 0;
while (chosenFruitItem < n) {
printf("\n(%d) Enter the item prefix: ", chosenFruitItem + 1);
char itemPrefix = ' ';
scanf_s(" %c", &itemPrefix, 1);
if (isItemExist(itemPrefixes, itemPrefix) == 1) {
printf("Error Item already exist");
continue;
}
else {
itemPrefixes[chosenFruitItem] = itemPrefix;
printf("Enter price for item (%c): ", itemPrefix);
scanf_s("%d", &itemPrices[chosenFruitItem]);
chosenFruitItem++;
}
}
displayMenu(itemPrefixes, itemPrices, n);
printf("\n**CUSTOMER PANEL***");
printf("\nWhat is your budget for today?: ");
scanf_s("%d", &budget);
printf("\nPlease enter Item Prefix from the menu to purchase: ");
scanf_s(" %c", &itemPurchased, 1);
if (withinBudget(budget, itemPurchased, itemPrefixes, itemPrices) == 1) {
printf("PURCHASS SUCCESS");
}
else
{
printf("INSUFFICENT BUDGET");
}
}
int isItemExist(char itemPrefixes[], char itemPrefix) {
for (int i = 0; i < n; i++) {
if (itemPrefixes[i] == itemPrefix) {
return 1;
}
}
return 0;
}
void displayMenu(char itemPrefixes[], int itemPrices[], int n) {
printf("\n*** ShopMenu ***");
printf("\nItem: \t Price: ");
for (int i = 0; i < n; i++) {
printf("\n%c:\t %d", itemPrefixes[i], itemPrices[i]);
}}
int withinBudget(int budget, char itemPurchased, char itemPrefixes[], int itemPrices[]) {
for (int i = 0; i < n; i++) {
if (itemPurchased == itemPrefixes[i] && itemPrices[i] < budget)
{
return 1;
}
return 0;
}
}
the output:
Please ident your code. Either simplest mistakes could go unnoticed because of this.
Here you have an auto one.
After doing this to your code, here's the last function:
int withinBudget(int budget, char itemPurchased, char itemPrefixes[], int itemPrices[]) {
for (int i = 0; i < n; i++) {
if (itemPurchased == itemPrefixes[i] && itemPrices[i] < budget) {
return 1;
}
return 0;
}
}
As you can see, return 0 is inside loop, it's working only if itemPurchased == itemPrefixes[0] && itemPrices[0] < budget as i will never be incremented.
So your function should be:
int withinBudget(int budget, char itemPurchased, char itemPrefixes[], int itemPrices[]) {
for (int i = 0; i < n; i++) {
if (itemPurchased == itemPrefixes[i] && itemPrices[i] < budget) {
return 1;
}
}
return 0;
}

How can I delete a user inputed element/data from an Array in Structure? [duplicate]

How to delete an element from the array of type structure? Let's say if I register an item and then want to delete it how can I do that? The delete function is at the end of the code. I want to delete the item by giving the varunummer (id number). Any one know how to do it?
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define WORDLENGTH 30
#define MAX 5
struct varor {
int varunummer;
char namn[WORDLENGTH];
int lagersaldo;
};
int readLine(char s[], int length);
int ifVarunummerExist(int varunummer, const struct varor reg[], int nrOfGoods);
void registerVaror(struct varor reg[], int *nrOfGoods);
void getPrint(const struct varor reg[], int nrOfGoods);
void avregristreraVaror(struct varor reg[], int nrOfGoods);
int main(void) {
struct varor vRegister[WORDLENGTH];
int nrOfGoods = 0;
int run = 1;
while (run) {
char choice;
printf("\n\t\tMeny - Lager Program\n\n\
(1) Register\n\b\b\b\b\
(2) Print\n\
(3) Delete\n\
(4) Quit\n");
scanf(" %c%*c", &choice);
if (choice=='1')
registerVaror(vRegister, &nrOfGoods);
if (choice=='2')
getPrint(vRegister, nrOfGoods);
if (choice=='3')
avregristreraVaror(vRegister, nrOfGoods);
else if (choice=='4')
run = 0;
}
return 0;
}
int ifVarunummerExist(int varunummer, const struct varor reg[], int nrOfGoods) {
int i;
for (i = 0; i < nrOfGoods; i++)
if(reg[i].varunummer == varunummer)
return i;
return -1;
}
int readLine(char s[], int length) {
int ch, i=0;
while (isspace(ch=getchar()));
while (ch != '\n' && ch != EOF) {
if (i < length)
s[i++] = ch;
ch = getchar();
}
s[i] = '\0';
return i;
}
void registerVaror(struct varor reg[], int *nrOfGoods) {
char namn[WORDLENGTH], tmp[WORDLENGTH];
int varunummer, lagersaldo;
if (*nrOfGoods == MAX) {
printf("\nError! Finns inte plats kvar!\n");
return;
}
printf("Ange varunummer: ");
scanf("%d", &varunummer);
if (ifVarunummerExist(varunummer, reg, *nrOfGoods) >= 0) {
printf("\nVarunummer finns redan!\n");
return;
}
reg[*nrOfGoods].varunummer = varunummer;
printf("Ange namn: ");
readLine(reg[*nrOfGoods].namn, WORDLENGTH);
printf("Ange lagersaldo :");
scanf("%d", &reg[*nrOfGoods].lagersaldo);
//reg[*nrOfGoods]=createVara(varunummer,namn,lagersaldo);
(*nrOfGoods)++;
}
void getPrint(const struct varor reg[], int nrOfGoods) {
int i;
printf("\nVarunummer \t Namn \t\t\t Lagersaldo\n");
for (i = 0; i < nrOfGoods; i++) {
printf(" %d \t\t %s \t\t\t %d\n",reg[i].varunummer,reg[i].namn,reg[i].lagersaldo);
}
}
void avregristreraVaror(struct varor reg[], int nrOfGoods) {
int run = 1;
while (run) {
char choice;
printf("\n (1) Delete \n (2) Exit");
scanf(" %c", &choice);
//DELETE IF CHOICE 1---------
if (choice == '1') {
int i, varunummer;
printf("Ange varunummer: ");
scanf("%d", &varunummer);
for (i = varunummer + 1; i < MAX; i++) {
reg[i - 1] = reg[i];
}
reg[i] = 0;
}
}
//QUIT TO MY MENU CHOICE 2--------
if (choice == '2')
run = 0;
}
You can try iterating through the array in a for loop UNTIL your varunummer is matched with the struct's property. Something along these lines (let's say you are searching for the member with varunummer = varunummerToLookFor), this shift all the elements in the array from the point onwards of your deletion by 1, hence, producing an array with the same sequence as before but with your wanted element removed. Hope that helps!
for(int i = 0, i < varorArraySize, i++){
if(varunummerToLookFor == varorArray[i].varunummer){
for (i = pos; i < varorArraySize - 1; i++)
{
varorArray[i] = varorArray[i + 1];
}
}
}

C programming call by reference pointer function to delete a member of a structure

This is for schoolwork and the question is asking to make a programme like a student database where I am able to input, print and remove students from the structure s using pointers function. However I am unable to delete the student records as something weird happens. The target student gets deleted but the rest of the students records(names only) are shifted, with only the first character being correct. Please help!
#include <stdio.h>
#include <string.h>
#define SIZE 50
typedef struct {
int id;
char name[50];
} Student;
void inputStud(Student *s, int size);
void printStud(Student *s, int size);
int removeStud(Student *s, int *size, char *target);
int main()
{
Student s[SIZE];
int size=0, choice;
char target[80], *p;
int result;
printf("Select one of the following options: \n");
printf("1: inputStud()\n");
printf("2: removeStud()\n");
printf("3: printStud()\n");
printf("4: exit()\n");
do {
printf("Enter your choice: \n");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter size: \n");
scanf("%d", &size);
printf("Enter %d students: \n", size);
inputStud(s, size);
break;
case 2:
printf("Enter name to be removed: \n");
scanf("\n");
fgets(target, 80, stdin);
if (p=strchr(target,'\n')) *p = '\0';
printf("removeStud(): ");
result = removeStud(s, &size, target);
if (result == 0)
printf("Successfully removed\n");
else if (result == 1)
printf("Array is empty\n");
else if (result == 2)
printf("The target does not exist\n");
else
printf("An error has occurred\n");
break;
case 3:
printStud(s, size);
break;
}
} while (choice < 4);
return 0;
}
void inputStud(Student *s, int size)
{
int i=0;
char *p,dummy[50];
while (i<size) {
printf("Student ID: \n");
scanf("%d",&((s+i)->id));
printf("Student Name: \n");
scanf("\n");
fgets((s+i)->name, 50,stdin);
if (p=strchr((s+i)->name,'\n')) *p = '\0';
i++;
}
}
void printStud(Student *s, int size)
{
int i;
printf("The current student list: \n");
if (size==0) printf("Empty array\n");
else {
for (i=0; i<size; i++) {
printf("Student ID: %d ",(s+i)->id);
printf("Student Name: %s\n",(s+i)->name);
}
}
}
int removeStud(Student *s, int *size, char *target)
{
int i,j,k;
if (*size==0) return 1;
for (i=0;i<*size;i++) {
if (strcmp(((s+i)->name),target)==0) {
--*size;
for (j=i; j<=*size; j++) {
k = j + 1;
*((s+j)->name) = *((s+k)->name);
(s+j)->id = (s+j+1)->id;
if ((s+j+1)->id=='\0') (s+j)->id = '\0';
}
return 0;
}
}
return 2;
}
you were almost there.
The problem is at line 97: *((s+j)->name) = *((s+k)->name);
To make it work, this instruction should be substituted with:
strcpy((s+j)->name, (s+k)->name);
Why:
you are coping with char arrays, so doing *((s+j)->name) = *((s+k)->name) means: "put the value of the first char of s+k->name into s+j->name first char".
Instead, you want to copy the whole name of s+k into the s+j name.
on how to use strcpy you can take a look here

Copying elements of array to a new one - C

I'm currently doing a school assignment and now I'm really stuck. The problem I have is that When I'm trying to copy the elements of the array dice to the array diceCheck the program goes in to some kind of infinite loop and I don't understand why. Help would be greatly appreciated!
Edit: It's in the bottom in the function printScores.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void printMenu(void);
void throwDice(int dice[], int nrOfDice, int nrOfDieValues);
void readDieValues (int dice[], int nrOfDice);
void printDice(const int dice[], int nrOfDice);
void printScores(const int dice[], int nrOfdice, int nrOfDieValues);
int isThreeOfAKind(const int dieValues[], int nrOfDieValues);
int isSmallStraight(const int dieValues[], int nrOfDieValues);
int main(void)
{
const int nrOfDice = 5;
const int nrOfDieValues = 6;
int dice[4], menuChoice = 0;
printMenu();
printf("\nMake your choice: ");
while(scanf("%d", &menuChoice) != -1)
{
switch (menuChoice)
{
case 0:
printMenu();
break;
case 1:
throwDice(dice, nrOfDice, nrOfDieValues);
printf("Make your choice: ");
break;
case 2:
readDieValues(dice, nrOfDice);
printf("Make your choice: ");
break;
case 3:
printDice(dice, nrOfDice);
printf("Make your choice: ");
break;
case 4:
printScores(dice, nrOfDice, nrOfDieValues);
break;
case -1:
return 0;
break;
default:
printf("Invalid choice!\n");
break;
}
}
return 0;
}
void printMenu()
{
printf("MENU:\n");
printf("0. Display the menu\n");
printf("1. Make a random throw\n");
printf("2. Enter die values for a throw\n");
printf("3. Display the die values for the throw\n");
printf("4. Display the score for the throw\n");
printf("-1. End program\n");
}
void throwDice(int dice[], int nrOfDice, int nrOfDieValues)
{
int choice, i;
printf("Enter seed (1 gives a random seed): ");
scanf("%d", &choice);
if(choice == 1)
{
srand(time(NULL));
for (i = 0; i < nrOfDice; i++)
{
dice[i] = ( rand() % nrOfDieValues) + 1;
}
printf("\n");
}
else
{
srand(choice);
for(i = 0; i < nrOfDice; i++)
{
dice[i] = ( rand() % nrOfDieValues) + 1;
}
printf("\n");
}
}
void readDieValues(int dice[], int nrOfDice)
{
int i;
for(i = 0; i < nrOfDice; i++)
{
printf("Die %d: ", (i+1));
scanf("%d", &dice[i]);
}
}
void printDice(const int dice[], int nrOfDice)
{
int i;
printf("Your dice: ");
for(i = 0; i < nrOfDice; i++)
{
printf("%d ", dice[i]);
}
printf("\n\n");
}
int isThreeOfAKind(const int dieValues[], int nrOfDieValues)
{
}
int isSmallStraight(const int dieValues[], int nrOfDieValues)
{
}
void printScores(const int dice[], int nrOfdice, int nrOfDieValues)
{
int diceCheck[4], i;
for(i = 0; i < nrOfdice; i++)
{
diceCheck[i] = dice[i];
printf("%d ", dice[i]); //these are just for myself to check if it worked
printf("%d ", diceCheck[i]); //these are just for myself to check if it worked
}
}
You have:
const int nrOfDice = 5;
but
int dice[4];
int diceCheck[4];
Your copying idea is correct but you are going one past the end of the array.
To avoid this sort of error, initialize both from the same expression, e.g.:
int dice[4];
const int nrOfDice = sizeof dice / sizeof dice[0];
or
const int nrOfDice = 4;
int dice[nrOfDice];
and inside the PrintScores function, instead of int diceCheck[4];, do:
int diceCheck[nrOfDice];

Resources