C Void ending issue - c

I am trying to write a simple parking arrangement code, I want to sort the capacity by 1000 vehicles, color, license plate and model
#include <stdio.h>
#include <stdlib.h>
void NewCar()
{
char model[1000][20];
char color [1000][20];
char number[1000][20];
int x = 1;
printf("\nModel: ");
scanf("%s",model[x]);
printf("Color: ");
scanf("%s",color[x]);
printf("Number: ");
scanf("%s",number[x]);
}
void CarList()
{
int x;
char model[1000][20];
char color [1000][20];
char number[1000][20];
for (x ; x >= 1 ; x--)
{
printf("\n%d. Car: %s %s %s",x,number[x],model[x],color[x]);
}
}
int main()
{
char model[1000][20];
char color [1000][20];
char number[1000][20];
char menu;
int x = 1;
flag:
printf("New Car(N)\nCar List(L)\n");
scanf("%s",&menu);
if (menu == "n" || menu == "N")
{
NewCar();
goto flag;
}
if (menu == "l" || menu == "L")
{
CarList();
goto flag;
}
}
when i don't use void, the code works but i have to use void
Example of the output I want;
1. Car Red Jeep FGX9425
2. Car Yellow Truck OKT2637
3. Car Green Sedan ADG4567
....

This is prefaced by my top comments.
Never use goto. Use (e.g.) a while loop.
Your scanf for menu would [probably] overflow.
As others have mentioned, a number of bugs.
I've refactored your code with your old code and some new code. This still needs more error checking and can be generalized a bit more, but, I've tested it for basic functionality:
#include <stdio.h>
#include <stdlib.h>
// description of a car
struct car {
char model[20];
char color[20];
char number[20];
};
int
NewCar(struct car *cars,int carcount)
{
struct car *car = &cars[carcount];
printf("\nModel: ");
scanf("%s", car->model);
printf("\nColor: ");
scanf("%s", car->color);
printf("\nNumber: ");
scanf("%s", car->number);
++carcount;
return carcount;
}
void
CarList(struct car *cars,int carcount)
{
struct car *car;
int caridx;
for (caridx = 0; caridx < carcount; ++caridx) {
car = &cars[caridx];
printf("%d. Car: %s %s %s\n",
caridx + 1, car->number, car->model, car->color);
}
}
int
main(int argc,char **argv)
{
#if 1
int carcount = 0;
struct car carlist[1000];
#endif
#if 0
char menu;
int x = 1;
#else
char menu[20];
#endif
// force out prompts
setbuf(stdout,NULL);
while (1) {
printf("New Car(N)\nCar List(L)\n");
#if 0
scanf("%s", &menu);
#else
scanf(" %s", menu);
#endif
// stop program
if ((menu[0] == 'q') || (menu[0] == 'Q'))
break;
switch (menu[0]) {
case 'n':
case 'N':
carcount = NewCar(carlist,carcount);
break;
case 'l':
case 'L':
CarList(carlist,carcount);
break;
}
}
return 0;
}
UPDATE:
As you said, there are a few minor errors, it's not a problem for me, but I can write errors if you want to know and fix them.(if you write the plate with a space between it, the code repeats the "new car car list" command many times)
Okay, I've produced an enhanced version that replaces the scanf with a function askfor that uses fgets. The latter will prevent [accidental] buffer overflow. And, mixing scanf and fgets can be problematic. Personally, I always "roll my own" using fgets as it can provide finer grain control [if used with wrapper functions, such as the askfor provided here]
Edit: Per chux, I've replaced the strlen for removing newline with a safer version that uses strchr:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRMAX 20
// description of a car
struct car {
char model[STRMAX];
char color[STRMAX];
char number[STRMAX];
};
// askfor -- ask user for something
void
askfor(const char *tag,char *ptr)
{
printf("Enter %s: ",tag);
fflush(stdout);
fgets(ptr,STRMAX,stdin);
// point to last char in buffer
// remove newline
#if 0
ptr += strlen(ptr);
--ptr;
if (*ptr == '\n')
*ptr = 0;
#else
// remove trailing newline [if it exists]
ptr = strchr(ptr,'\n');
if (ptr != NULL)
*ptr = 0;
#endif
}
int
NewCar(struct car *cars,int carcount)
{
struct car *car = &cars[carcount];
askfor("Model",car->model);
askfor("Color",car->color);
askfor("Number",car->number);
++carcount;
return carcount;
}
void
CarList(struct car *cars,int carcount)
{
struct car *car;
int caridx;
for (caridx = 0; caridx < carcount; ++caridx) {
car = &cars[caridx];
printf("%d. Car: %s %s %s\n",
caridx + 1, car->number, car->model, car->color);
}
}
int
main(int argc,char **argv)
{
int carcount = 0;
struct car carlist[1000];
char menu[STRMAX];
// force out prompts
setbuf(stdout,NULL);
while (1) {
askfor("\nNew Car(N)\nCar List(L)",menu);
// stop program
if ((menu[0] == 'q') || (menu[0] == 'Q'))
break;
switch (menu[0]) {
case 'n':
case 'N':
carcount = NewCar(carlist,carcount);
break;
case 'l':
case 'L':
CarList(carlist,carcount);
break;
}
}
return 0;
}
UPDATE #2:
Thank you for your bug fix, but as I said in my question, I have to do the "New car" feature using void. You did it with int, can you do it with void?
Okay. When you said "using void", what you meant wasn't totally clear to me [or some others]. There were enough bugs that they overshadowed some other considerations.
So, I have to assume that "using void" means that the functions return void.
Your original functions were defined as void NewCar() and void CarList(). Those could not have done the job as is, so they had to be changed.
If you have similar criteria, a better way to phrase that would be:
I must create two functions, with the following function signatures ...
Anyway, here's the updated code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRMAX 20
// description of a car
struct car {
char model[STRMAX];
char color[STRMAX];
char number[STRMAX];
};
// askfor -- ask user for something
void
askfor(const char *tag,char *ptr)
{
printf("Enter %s: ",tag);
fflush(stdout);
fgets(ptr,STRMAX,stdin);
// remove trailing newline [if it exists]
ptr = strchr(ptr,'\n');
if (ptr != NULL)
*ptr = 0;
}
void
NewCar(struct car *cars,int *countptr)
{
int carcount = *countptr;
struct car *car = &cars[carcount];
askfor("Model",car->model);
askfor("Color",car->color);
askfor("Number",car->number);
carcount += 1;
*countptr = carcount;
}
void
CarList(struct car *cars,int carcount)
{
struct car *car;
int caridx;
for (caridx = 0; caridx < carcount; ++caridx) {
car = &cars[caridx];
printf("%d. Car: %s %s %s\n",
caridx + 1, car->number, car->model, car->color);
}
}
int
main(int argc,char **argv)
{
int carcount = 0;
struct car carlist[1000];
char menu[STRMAX];
// force out prompts
setbuf(stdout,NULL);
while (1) {
askfor("\nNew Car(N)\nCar List(L)",menu);
// stop program
if ((menu[0] == 'q') || (menu[0] == 'Q'))
break;
switch (menu[0]) {
case 'n':
case 'N':
#if 0
carcount = NewCar(carlist,carcount);
#else
NewCar(carlist,&carcount);
#endif
break;
case 'l':
case 'L':
CarList(carlist,carcount);
break;
}
}
return 0;
}
However, given your original functions, it may be possible that the signatures have to be: void NewCar(void) and void CarList(void) and that the car list variables must be global scope.
This would be a less flexible and desirable way to do things, but here is a version that uses only global variables for the lists:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRMAX 20
// description of a car
struct car {
char model[STRMAX];
char color[STRMAX];
char number[STRMAX];
};
#if 1
int carcount = 0;
struct car carlist[1000];
#endif
// askfor -- ask user for something
void
askfor(const char *tag,char *ptr)
{
printf("Enter %s: ",tag);
fflush(stdout);
fgets(ptr,STRMAX,stdin);
// remove trailing newline [if it exists]
ptr = strchr(ptr,'\n');
if (ptr != NULL)
*ptr = 0;
}
void
NewCar(void)
{
struct car *car = &carlist[carcount];
askfor("Model",car->model);
askfor("Color",car->color);
askfor("Number",car->number);
carcount += 1;
}
void
CarList(void)
{
struct car *car;
int caridx;
for (caridx = 0; caridx < carcount; ++caridx) {
car = &carlist[caridx];
printf("%d. Car: %s %s %s\n",
caridx + 1, car->number, car->model, car->color);
}
}
int
main(int argc,char **argv)
{
#if 0
int carcount = 0;
struct car carlist[1000];
#endif
char menu[STRMAX];
// force out prompts
setbuf(stdout,NULL);
while (1) {
askfor("\nNew Car(N)\nCar List(L)",menu);
// stop program
if ((menu[0] == 'q') || (menu[0] == 'Q'))
break;
switch (menu[0]) {
case 'n':
case 'N':
#if 0
carcount = NewCar(carlist,carcount);
#else
NewCar();
#endif
break;
case 'l':
case 'L':
#if 0
CarList(carlist,carcount);
#else
CarList();
#endif
break;
}
}
return 0;
}

Related

Structur Pointer C

I know I for sure misunderstand how to use pointers again. So here is my code. Would be nice if you all can help me. The program is simple. You write values in a structure array and print them out. Even so it would be nice if someone could explain to me when to use double pointers and how to use them probably.
#include <stdio.h>
#include <stdlib.h>
#define MAXA 3
typedef enum{
FOOD,
ART,
OTHERS
}TKindOfArticle;
typedef struct{
int number;
char description[31+1];
int sellingGrossPrice;
int vat;
int minimumStockLevel;
TKindOfArticle kindOf;
}TArticle;
void readOneArticle(TArticle* arti);
int readMaxArticle(TArticle* arti[]);
void printfOneArticle(TArticle arti);
void printfMaxArticle(TArticle *arti[],int read);
int main()
{
TArticle arti[MAXA];
int howMany;
howMany = readMaxArticle(&arti);
printfMaxArticle(&arti,howMany);
return 0;
}
void readOneArticle(TArticle* arti){
printf("Number: ");
scanf("%d", &(arti->number));
printf("Descrip: ");
scanf("%s", &(arti->description));
printf("SellGrossPrice: ");
scanf("%d",&(arti->sellingGrossPrice));
printf("MinimumStock: ");
scanf("%d",&(arti->minimumStockLevel));
printf("Kind of article (0: Food, 1: Art, 2: Others): ");
scanf("%d",&(arti->kindOf));
if(arti->kindOf == FOOD){
arti->vat= arti->sellingGrossPrice*1.1;
} else if(arti->kindOf == ART){
arti->vat= arti->sellingGrossPrice*1.13;
}else if(arti->kindOf == OTHERS){
arti->vat= arti->sellingGrossPrice*1.2;
}
}
int readMaxArticle(TArticle* arti[]){
int read;
int i=0;
printf("Max Elements (max. 3): ");
scanf("%d",&read);
if(read>MAXA){
printf("Error");
} else{
for(i=0; i<read;i++){
readOneArticle(arti[i]);
printf("\n");
printf("Number: %d\nDescrip.: %s\nSell Gross: %d\nVat: %d\nMin. Stock: %d\n",
(*arti[i]).number,(*arti[i]).description,
(*arti[i]).sellingGrossPrice,(*arti[i]).vat,(*arti[i]).minimumStockLevel);
}
}
return read;
}
void printfOneArticle(TArticle arti){
printf("Number: %d\nDescrip.: %s\nSell Gross: %d\nVat: %d\nMin. Stock: %d\n",
arti.number,arti.description,
arti.sellingGrossPrice,arti.vat,arti.minimumStockLevel);
switch(arti.kindOf){
case 0: printf("Kind: Food\n");
break;
case 1: printf("Kind: Art\n");
break;
case 2: printf("Kind: Others\n");
break;
}
}
void printfMaxArticle(TArticle *arti[],int read){
if(read>MAXA){
} else{
for(int i=0; i<read;i++){
printfOneArticle(*arti[i]);
printf("\n");
}
}
}
You are creating an array of structures: TArticle arti[MAXA];
But when you call readMaxArticle(&arti) function you pass pointer to array of TArticle. TArticle *arti[] it reads like this - arti is array of pointers to TArticle. But you want to pass pointer to array of TArticle. It won't compile anyway.
error: cannot convert 'TArticle (*)[3]' to 'TArticle**'
You might want to look at how to read C declaration and if you want to practice visit this site.

C how to run a loop in the background

I am making a "Clicker-Game". It's my first real game that I'm doing alongside school. I got all of the game code complete but I want to have a loop in the background that adds geldps(money per second) after every second.
I tried threads but I don't really understand it and we won't learn that until next year, so I´m asking, if anyone can either tell me a better way to make a loop in the background that runs independent from the main program, and can just add geldps to geld every second. Thanks.
PS: I am sorry for the German variables. Ask me if you don't know what sth means or anything, and it´s probably not very well organised and everything.
#include <stdio.h>
int geldps=0,geld=0;
int main()
{
int stand=0, oil=0, Mine=0, Bank=0,standzahl=100, Minezahl=500, Bankzahl=1000, oilzahl=10000, Werkzeug=0, Werkzeugzahl=10;
char input, input2;
float faktor;
do
{
system("cls");
faktor=1+Werkzeug/10;
printf("%c%c%c%c%c%c%c%c%c%c%c\n",201,205,205,205,205,205,205,205,205,205,187);
printf(" %d$\n",geld);
printf("%c%c%c%c%c%c%c%c%c%c%c\n",200,205,205,205,205,205,205,205,205,205,188);
printf(" Space to get money\n U to go to Upgrades\n Escape to leave");
input=getch();
if(input==32)
{
geld=geld+faktor;
continue;
}
if(input == 117 || input == 85)
{
system("cls");
do
{
system("cls");
printf(" 0 - Tools(10 for 1 more Money)(%d)(%d$)\n 1 - Lemon Stands(%d)(%d$)\n 2 - Mines(%d)(%d$)\n 3 - Banks(%d)(%d$)\n 4 - Oil Refinerys(%d)(%d$)\nBackspace to go back", Werkzeug, Werkzeugzahl, stand, standzahl, Mine, Minezahl, Bank, Bankzahl, oil, oilzahl);
input2=getch();
if(input2== 48)
{
if(geld<Werkzeugzahl)
{
system("cls");
printf("Not enough money(%d/%d$)\n",Werkzeugzahl,geld);
system("pause");
continue;
}
geld=geld-Werkzeugzahl;
Werkzeug++;
Werkzeugzahl=Werkzeugzahl+Werkzeugzahl/10;
}
if(input2== 49)
{
if(geld<standzahl)
{
system("cls");
printf("Not enough money(%d/%d$)\n",standzahl,geld);
system("pause");
continue;
}
geld=geld-standzahl;
stand++;
standzahl=standzahl+standzahl/10;
}
if(input2== 50)
{
if(geld<Minezahl)
{
system("cls");
printf("Not enough money(%d/%d$)\n",Minezahl,geld);
system("pause");
continue;
}
geld=geld-Minezahl;
Mine++;
Minezahl=Minezahl+Minezahl/10;
geldps=geldps+1;
}
if(input2== 51)
{
if(geld<Bankzahl)
{
system("cls");
printf("Not enough money(%d/%d$)\n",Bankzahl,geld);
system("pause");
continue;
}
geld=geld-Bankzahl;
Bank++;
Bankzahl=Bankzahl+Bankzahl/10;
geldps=geldps+10;
}
if(input2== 52)
{
if(geld<oilzahl)
{
system("cls");
printf("Not enough money(%d/%d$)\n",oilzahl,geld);
system("pause");
continue;
}
geld=geld-oilzahl;
oil++;
oilzahl=oilzahl+oilzahl/10;
geldps=geldps+100;
}
}
while(input2!=8);
}
}
while(input!=27);
return 0;
}
update: I was procrastinating and cleaned and improved your code. At the end of this answer.
If all you need is for a number to be consistently incremented based on time, add a function that updates a value based on time.
Here's an example showing not only how to do that but also how to compartmentalize your code into functions and how to use better code formatting and variable names.
#include <stdio.h> // printf()
#include <time.h> // time()
#include <stdlib.h> // random()
#include <unistd.h> // sleep()
int updateValue(int lastValue, int amountPerSecond) {
static time_t lastTime = -1;
time_t currentTime = time(NULL);
int newValue = lastValue;
if (lastTime != -1) {
newValue += amountPerSecond * (currentTime - lastTime);
}
lastTime = currentTime;
return newValue;
}
void seedRandom() {
// Don't use this in production code.
srandom(time(NULL));
}
int sleepRandomly() {
const int SLEEP_RANGE_IN_SECS = 5;
// sleep( 0..5 seconds )
int timeToSleep = random() % (SLEEP_RANGE_IN_SECS + 1);
sleep(timeToSleep);
return timeToSleep;
}
int main() {
const int AMOUNT_PER_SECOND = 5;
int value = 0;
// How many times to run the loop
int numCycles = 5;
seedRandom();
// Initialize the updateValue() start time
value = updateValue(value, AMOUNT_PER_SECOND);
while (numCycles--) {
int amountSlept = sleepRandomly();
int newValue = updateValue(value, AMOUNT_PER_SECOND);
printf("Slept %d seconds.", amountSlept);
printf("Value updated: %10d + (%d secs * %4d amount/secs) = %10d\n",
value, amountSlept, AMOUNT_PER_SECOND, newValue);
value = newValue;
}
return 0;
}
Cleaned up version of your code, and then I just kept improving it.
#include <stdio.h> // printf()
#include <string.h> // strlen()
#include <stdarg.h> // vsnprintf()
#include <unistd.h> // STDIN_FILENO
#include <sys/time.h> // gettimeofday()
#include <time.h>
#include <termios.h>
#include <errno.h>
#include <signal.h>
// TODO: convert the menus to tables:
// key - desc count cost effect
// TODO: add all income sources in a list so it's easy to add more
// without changing code
// TODO: the current pricing is off
// TODO: convert to C++ so we can use classes
// TODO: only use one menu, it's nicer to use
// one global value so we can ensure that we restore
// stdin's terminal settings
struct termios g_oldStdinTermios;
int g_keepGoing = 1;
typedef struct {
int count;
int zahl;
int zahlIncrement;
int geldPerSecondIncrement;
} IncomeSource;
typedef struct {
char lastMessage[100];
// try to avoid global variables, pass them instead
// one variable per line
int geld;
int geldPerSecond;
int geldPerClick;
IncomeSource werkzeug;
IncomeSource stand;
// Use consistent capitalization: sound be "mine"
IncomeSource mine;
IncomeSource bank;
IncomeSource oil;
} Values;
void setLastMessage(Values *values, const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
(void) vsnprintf(values->lastMessage, sizeof(values->lastMessage), fmt, ap);
va_end(ap);
}
void clearLastMessage(Values *values) {
// clear lastMessage after valid choice
values->lastMessage[0] = '\0';
}
void initializeValues(Values *values) {
clearLastMessage(values);
// use spaces around assignment and operators
values->geldPerSecond = 0;
values->geld = 10000;
// count, cost, cost increment (1/n), geldPerSecond increment
values->werkzeug = (IncomeSource){0, 10, 10, 0};
// BUG: number of stands doesn't increase geld per second
// or geld per click
values->stand = (IncomeSource){0, 100, 10, 0};
values->mine = (IncomeSource){0, 500, 10, 1};
values->bank = (IncomeSource){0, 1000, 10, 10};
values->oil = (IncomeSource){0, 10000, 10, 100};
values->geldPerClick = 1 + values->werkzeug.count / 10;
}
void clearScreen() {
// use ANSI escape sequences
const char *ANSI_MOVE_TO_1_1 = "\x1B[1;1H";
const char *ANSI_CLEAR_SCREEN = "\x1B[2J";
printf("%s%s", ANSI_CLEAR_SCREEN, ANSI_MOVE_TO_1_1);
}
char upcase(char c) {
if (c < 'a' || c > 'z') {
return c;
}
return 'A' + (c - 'a');
}
void setNonBlockingBufferingStdinTermios() {
struct termios new_;
tcgetattr(STDIN_FILENO, &g_oldStdinTermios);
new_ = g_oldStdinTermios;
new_.c_lflag &= ~ICANON;
tcsetattr(STDIN_FILENO, TCSANOW, &new_);
}
void restoreStdinTermios() {
tcsetattr(STDIN_FILENO, TCSANOW, &g_oldStdinTermios);
}
long getElapsedTimeInMs(struct timeval *start) {
struct timeval now;
gettimeofday(&now, NULL);
// in microseconds
long elapsed = ((now.tv_sec - start->tv_sec) * 1000000
+ now.tv_usec - start->tv_usec);
return elapsed / 1000;
}
char getCharacter() {
struct timeval start;
gettimeofday(&start, NULL);
char input = -1;
while (read(STDIN_FILENO, &input, 1) == -1
&& errno == EAGAIN
&& getElapsedTimeInMs(&start) < 500) {
}
return upcase(input);
}
void updateGeld(Values *values) {
static time_t lastTime = -1;
time_t currentTime = time(NULL);
if (lastTime != -1) {
values->geld += values->geldPerSecond * (currentTime - lastTime);
}
lastTime = currentTime;
}
void printHeader(Values *values) {
const char *UPPER_LEFT = "\u2554";
const char *UPPER_RIGHT = "\u2557";
const char *LOWER_LEFT = "\u255a";
const char *LOWER_RIGHT = "\u255d";
const char *HORIZONTAL = "\u2550";
const char *VERTICAL = "\u2551";
updateGeld(values);
// Automatically expand the box as the size
// of geld grows.
const int BORDER_WIDTH = 3;
char geldStr[20];
snprintf(geldStr, sizeof(geldStr), "$ %d", values->geld);
// Move code used more than once into its own function
clearScreen();
printf("%s", UPPER_LEFT);
for (int i = 0; i < (2 * BORDER_WIDTH + strlen(geldStr)); i++) {
printf("%s", HORIZONTAL);
}
printf("%s\n", UPPER_RIGHT);
// use spaces around commas
printf("%s %s %s %s\n",
VERTICAL, geldStr, VERTICAL, values->lastMessage);
printf("%s", LOWER_LEFT);
for (int i = 0; i < (2 * BORDER_WIDTH + strlen(geldStr)); i++) {
printf("%s", HORIZONTAL);
}
printf("%s\n", LOWER_RIGHT);
}
void upgrade(Values *values, IncomeSource *source) {
if (values->geld < source->zahl) {
setLastMessage(values, "Not enough money(%d/%d$)",
source->zahl, values->geld);
return;
}
clearLastMessage(values);
values->geld -= source->zahl;
source->count++;
source->zahl += source->zahl / source->zahlIncrement;
values->geldPerSecond += source->geldPerSecondIncrement;
}
char getUpgradeInput(Values *values) {
clearScreen();
printHeader(values);
printf(" 0 - Tools(10 for 1 more Money)(%d)(%d$)\t\t+%d/click\n",
values->werkzeug.count, values->werkzeug.zahl, values->geldPerClick);
printf(" 1 - Lemon Stands(%d)(%d$)\t\t\t+%d/sec\n",
values->stand.count, values->stand.zahl,
values->stand.count * values->stand.geldPerSecondIncrement);
printf(" 2 - Mines(%d)(%d$)\t\t\t\t+%d/sec\n",
values->mine.count, values->mine.zahl,
values->mine.count * values->mine.geldPerSecondIncrement);
printf(" 3 - Banks(%d)(%d$)\t\t\t\t+%d/sec\n",
values->bank.count, values->bank.zahl,
values->bank.count * values->bank.geldPerSecondIncrement);
printf(" 4 - Oil Refinerys(%d)(%d$)\t\t\t+%d/sec\n",
values->oil.count, values->oil.zahl,
values->oil.count * values->oil.geldPerSecondIncrement);
printf(" Q - Back to main menu\n");
printf("> ");
fflush(stdout);
return getCharacter();
}
void upgradeLoop(Values *values) {
char input = ' ';
while (input != 'Q' && g_keepGoing) {
input = getUpgradeInput(values);
switch (input) {
case '0':
upgrade(values, &values->werkzeug);
values->geldPerClick = 1 + values->werkzeug.count / 10;
break;
case '1':
upgrade(values, &values->stand);
break;
case '2':
upgrade(values, &values->mine);
break;
case '3':
upgrade(values, &values->bank);
break;
case '4':
upgrade(values, &values->oil);
break;
case 'Q':
break;
default:
break;
}
}
}
char getMainInput(Values *values) {
printHeader(values);
// make this easier to read in the code...
printf(" _ - [Space] get money\n");
printf(" U - Upgrades\n");
printf(" Q - Quit\n");
printf("> ");
fflush(stdout);
return getCharacter();
}
void mainLoop(Values *values) {
char input = ' ';
// while..do is easier to read and understand than do..while
while (input != 'Q' && g_keepGoing) {
// Encapsulate code in functions to make your program's logic
// easier to follow
input = getMainInput(values);
// Use a switch statement here and use character values
// rather than integers
switch (input) {
case ' ':
values->geld += values->geldPerClick;
clearLastMessage(values);
break;
case 'U':
upgradeLoop(values);
clearLastMessage(values);
case 'Q':
break;
default:
break;
}
};
}
void sigintHandler(int signal) {
printf("SIGINT received, cleaning up.\n");
restoreStdinTermios();
g_keepGoing = 0;
}
int main() {
Values values;
initializeValues(&values);
setNonBlockingBufferingStdinTermios();
signal(SIGINT, sigintHandler);
mainLoop(&values);
restoreStdinTermios();
return 0;
}

Refactoring: Very similar switch cases

I have several struct declared which contain different data. I also have an enum that corresponds to those structures. There are several places in my code where I need to access information about the structures and I'm doing it via the enum. This results in few switch statements that return this information.
I've enclosed those switch statements in their own functions in order to re-use wherever possible. This resulted in three functions that look very similar.
Example psuedo-code:
#include <stdio.h>
typedef struct
{
int varA;
char varB;
} A;
typedef struct
{
int varA;
int varB;
int varC;
} B;
typedef struct
{
int varA;
short varB;
} C;
typedef enum { structA, structB, structC } STRUCT_ENUM;
int returnSize(STRUCT_ENUM structType)
{
int retVal = 0;
switch(structType)
{
case structA:
retVal = sizeof(A);
break;
case structB:
retVal = sizeof(B);
break;
case structC:
retVal = sizeof(C);
break;
default:
break;
}
return retVal;
}
void printStructName(STRUCT_ENUM structType)
{
switch(structType)
{
case structA:
printf("Struct: A\r\n");
break;
case structB:
printf("Struct: B\r\n");
break;
case structC:
printf("Struct: C\r\n");
break;
default:
break;
}
}
void createDataString(STRUCT_ENUM structType, char* output, unsigned char* input)
{
switch(structType)
{
case structA:
{
A a = *(A*)input;
sprintf(output, "data: %d, %d", a.varA, a.varB);
break;
}
case structB:
{
B b = *(B*)input;
sprintf(output, "data: %d, %d, %d", b.varA, b.varB, b.varC);
break;
}
case structC:
{
C c = *(C*)input;
sprintf(output, "data: %d, %d", c.varA, c.varB);
break;
}
default:
break;
}
}
int main(void) {
char foobar[50];
printf("Return size: %d\r\n", returnSize(structA));
printStructName(structB);
C c = { 10, 20 };
createDataString(structC, foobar, (unsigned char*) &c);
printf("Data string: %s\r\n", foobar);
return 0;
}
Those free functions basically contain the same switch with different code placed in the cases. With this setup, adding new struct and enum value results in three places in the code that needs changing.
The question is: is there a way to refactor this into something more maintainable? Additional constraint is that the code is written in C.
EDIT: online example: http://ideone.com/xhXmXu
You can always use static arrays and use STRUCT_ENUM as the index. Given the nature of your functions, I don't really know if you would consider it more maintainable, but it's an alternative I usually prefer, examples for names and sizes:
typedef enum { structA, structB, structC, STRUCT_ENUM_MAX } STRUCT_ENUM;
char *struct_name[STRUCT_ENUM_MAX] = {[structA] = "Struct A", [structB] = "Struct B", [structC] = "Struct C"};
size_t struct_size[STRUCT_ENUM_MAX] = {[structA] = sizeof(A), [structB] = sizeof(B), [structC] = sizeof(C)};
for printing content you can keep a similar array of functions receiving a void * that will print the value of this argument.
Edit:
Added designated initializers as per Jen Gustedt's comment.
You can make it into a single function and a single switch, with an additional parameter. Like so
int enumInfo(STRUCT_ENUM structType, int type) // 1 = returnSize 2 = printStructName
{
int retVal = 0;
switch(structType)
{
case structA:
If ( type == 1 ) { retVal = sizeof(A); }
else { printf("Struct: A"); }
break;
case structB:
If ( type == 1 ) { retVal = sizeof(B); }
else { printf("Struct: B"); }
break;
case structC:
If ( type == 1 ) { retVal = sizeof(C); }
else { printf("Struct: C"); }
break;
default:
break;
}
return retVal;
}

Declaring Int variables causes segmentation fault?

Hey guys I'm having a really peculiar segmentation fault coming up in my program. This program is suppose to automate the card game "war" and so far I've been able to build two randomized half decks for both players. Which would appear to show that enqueue is working correct. I was also able to dequeue all the values and they appeared in the correct order. However inside main if I uncomment the integer declarations in main the program segfaults every time. I can not for the life of me figure out how simple declarations could cause faults. Please note this is my only second assignment for using queues.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
typedef struct node
{
int value;
int suit;
char*sname;
char*txt;
struct node *next;
} node;
int isempty(node *base){
if (base==NULL)
{return 1;}
else
return 0;
}
void printlist(node *base){
node *current=base;
if(base==NULL)
{
printf("The List is empty!\n");
return;
}
else
{
printf("Content: \n");
int count=0;
while(current!=NULL){
count++;
printf("%s \tof \t%s\n",current->txt,current->sname);
current=current->next;
}
printf("\nCount:%d\n",count);
}
}
char* valname(int n){
char *name;
switch(n)
{
case 0:name="two";break;
case 1:name="three";break;
case 2:name="four";break;
case 3:name="five";break;
case 4:name="six";break;
case 5:name="seven";break;
case 6:name="eight";break;
case 7:name="nine";break;
case 8:name="ten";break;
case 9:name="Jack";break;
case 10:name="Queen";break;
case 11:name="King";break;
case 12:name="Ace";break;
default:printf("Broken\n");exit(1);
}
return(name);
}
char* suitname(int n){
char *name;
switch(n){
case 0:name="Hearts";break;
case 1:name="Spades";break;
case 2:name="Clubs";break;
case 3:name="Diamonds";break;
default:printf("Broken\n");exit(1);
}
return(name);
}
void enqueue(node **base,int item){
node *nn,*current=*base;
nn=malloc(sizeof(node));
if(*base==NULL)
{
*base=nn;
}
else
{
while(current->next!=NULL){
current=current->next;
}
current->next=nn;
}
nn->value=item;
nn->txt=valname(item%13);
nn->sname=suitname(item/13);
nn->next=NULL;
}
int dequeue(node **base){
node *current=*base,*temp;
if (isempty(*base)==0){
int giveback=current->value;
if(current->next==NULL)
{
free(*base);
*base=NULL;
}
else
{
temp=current->next;
free(current);
*base=temp;
}
return giveback;
}else{return -1;}
}
void createdecks(node **deck1,node **deck2){
int i=0;
int thenumber=0;
int deck[52]={0};
for(i=0;i<26;i++){
thenumber=rand()%52;
if(deck[thenumber]==0){
//add to list
enqueue(deck1,thenumber);
deck[thenumber]=1;
}
else
{
i--;
}
}
for(i=0;i<26;i++){
thenumber=rand()%52;
if(deck[thenumber]==0){
//add to list
enqueue(deck2,thenumber);
deck[thenumber]=1;
}
else
{
i--;
}
}
}
int main(void){
node *d1,*d2,*warholder;
//int c1=0,c2=0; //THIS LINE!!!!!!!!!!!
srand(time(NULL));
createdecks(&d1,&d2);
//printlist(d1);
//printlist(d2);
int i=0;
for(i=0;i<26;i++)
printf("%d ",dequeue(&d1)); //return testing
printf("\n");
printlist(d1);
}
Professor's example function
char * namenum( int num)
{
char * name;
switch(num)
{
case 0:
name = "zero"; break;
case 1:
name = "one"; break;
case 2:
name = "two"; break;
case 3:
name = "three"; break;
case 4:
name = "four"; break;
case 5:
name = "five"; break;
case 6:
name = "six"; break;
case 7:
name = "seven"; break;
case 8:
name = "eight"; break;
case 9:
name = "nine"; break;
default:
printf("Invalid Number generated\n");
exit(1);
}
return name;
}
I briefly looked at the code, and it looks to me like you have an uninitialized-variable problem. You declare this in main():
node *d1,*d2,*warholder;
And then you pass it to createdecks(), which in turn calls enqueue(). enqueue() assumes that the pointers are initialized.
Try to initialize d1 and d2 in main():
node *d1,*d2,*warholder;
d1 = d2 = warholder = NULL;
Its not due to declaring int. You have not allocated memory to char *name on several times before using it. for example
char* valname(int n){
char *name;
allocate memory using malloc() before using name after above code
char* suitname(int n){
char *name;
same mistake again
If you want to avoid such situation use array instead of pointer

I'm facing a runtime error in a c program that should convert from infix to postfix notation

I'm writing a program that should read equations from a txt file and fill them in a linked-list, check their validity and then convert each valid equation to post-fix notation and calculate the final result. Then write them to a file or print them on the console depends on the user choice. Following is what I've already done, I know my code is really long but I posted it all in order to make my question more clear:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node *ptr;
struct node
{
char eq[100];
char pstfix[100];
double result;
ptr next;
int topPST;
int topOP;
int validity;
};
typedef ptr list;
typedef ptr position;
list l;
void menu(); // prints the menu
void readFile(list l); //reads data from a file
int opPriority(char operators[],char operation,int top) ; // check the priority of a given operation
void isValid(position p);//Function to check the validity of each equation.
void convert(list l); // to convert from infix to postfix
void getResult(list l); // to calculate the result of an equation
double calculate(char operation, int op1,int op2);//To return the value in each step when getting the result
void showValidity(list l); // print the equations and show the ones that have errors
void acceptEq(list l); // Let the user enter equations on the console screen
void fillInfix(position p, char c[]);//A function to fill the array of infix in the node.
int isNum(char val);//returns if the value passed to it is a number or character.
void writeToFile(list l);//Write to the file
void showConsole(list l);//Show the final results on the console
int main()
{
printf("\t\t\t*Data Structure\tSecond project*\n\n\t\t\t*Convert from infix to postfix*\n\n");
menu();
l=(list)malloc(sizeof(struct node));
return 0;
}
//Function to print the menu and let the program work depending on the choice.
void menu()
{
system("cls");
int choice;
printf("\t\t\t\tMenu\n\n\t\t\t1.Read equations from file.\n\t\t\t2.Check validity.\n\t\t\t3.Convert to postfix.\n\t\t\t4.Add more equations to the file.\n\t\t\t\n\t\t\t5.Calculate Results.\n\t\t\t6.Write results to file.\n\t\t\t7.Show results on the console.\n\t\t\t8.End.\n\n\t\t\tEnter Your choice number please\n\t\t\t");
scanf("%d",&choice);
switch (choice)
{
case 1: readFile(l);
break;
case 2: isValid(l);
break;
case 3: convert(l);
break;
case 4: acceptEq(l);
break;
case 5: getResult(l);
break;
case 6: writeToFile(l);
break;
case 7: showConsole(l);
break;
case 8: exit(0);
}
}
//The following function should read equations from a file specified by the user
void readFile(list l)
{
system("cls");
char fileName[50];
FILE *eqFile;
printf("\t\t\tEnter the title of the file please\n\t\t\t");
scanf("\t\t\t%s",fileName);
eqFile=fopen(fileName,"r");
//To ensure the existence of the requested file.
while (eqFile == NULL)
{
printf("\t\t\tThe file you asked for does not exist. Enter another name or enter 'back' to return to menu\n\t\t\t");
scanf("\t\t\t%s",fileName);
if(strcmp(fileName,"back")==0) menu();
else eqFile=fopen(fileName,"r");
}
(l)->next=(position)malloc(sizeof (struct node));
position temp=(l)->next;
char line[100];
while (temp != NULL){
while (fgets(line,sizeof line, eqFile) != NULL)
{
isValid(temp);
if ((temp)->validity) fillInfix(temp,line);
temp=(temp)->next;
(temp)->next=NULL;
}
}
fclose(eqFile);
int choice;
printf("\t\t\tData Read Successfully\n\t\t\tEnter 0 to exit or 1 to return to menu\n\t\t\t");
scanf("%d",&choice);
if (choice) menu();
else exit(0);
}
void isValid(list l)
{
system("cls");
position temp;
temp=l;
int i,count=0;
while((temp)->next!=NULL)
{
for (i=0;i<100;i++)
{
if (((l)->eq[i]=='+' && (l)->eq[i+1]=='*') || ((l)->eq[i]=='-' && (l)->eq[i+1]=='*')|| ((l)->eq[i]=='*' && (l)->eq[i+1]=='/') || ((l)->eq[i]=='/' && (l)->eq[i+1]=='+')|| ((l)->eq[i]=='/' && (l)->eq[i+1]=='-') || (l)->eq[i]==' ')
count++;
}
if (count!=0) (temp)->validity=0;
temp=(temp)->next;
}
int choice;
printf("\t\t\tChecking validity is done enter 0 to quite or 1 to return to menu\n\t\t\t");
scanf("%d",&choice);
if(choice) menu();
else exit(0);
}
void fillInfix(position p, char line[])
{
int i;
for (i=0;i<100;i++)
{
while (line[i]!='\0')
{
(p)->eq[i]=line[i];
}
}
}
void push(char st[],char element, int top)
{
++top;
st[top]=element;
}
char pop(char st[],int top)
{
char elemnt=st[top];
--top;
return elemnt;
}
int opPriority(char operators[], char operation, int top)
{
if ((operation=='*' && operators[top]=='-') || (operation=='*' && operators[top]=='+') || (operation=='*' && operators[top]=='/') || (operation=='/' && operators[top]=='-')|| (operation=='/' && operators[top]=='+') || (operation=='+' && operators[top]=='-')) return 0;
else
if ((operation=='(' && operators[top]=='*') || (operation=='(' && operators[top]=='/') || (operation=='(' && operators[top]=='+') || (operation=='(' && operators[top]=='-')) return 0;
else if (operation==')') return 2;
else
return 1;
}
int isNum(char val)
{
if (val!='+' && val!='-' && val!='*' && val!='/') return 1;
else return 0;
}
void convert(list l)
{
position temp=l;
int i;
char operators[100];
while ((temp)->next != NULL)
{
temp=(temp)->next;
if ((temp)->validity)
{
for (i=0;i<100;i++)
{
if (isNum((temp)->eq[i])) push((temp)->pstfix,(temp)->eq[i],(temp)->topPST);
else
{
int priority=opPriority(operators,(temp)->eq[i],(temp)->topOP);
if (priority==1)
{
push((temp)->pstfix,pop(operators,(temp)->topOP),(temp)->topPST);
push(operators,(temp)->eq[i],(temp)->topOP);
}
else
if (priority ==0) push(operators,(temp)->eq[i],(temp)->topOP);
else
if (priority==2)
{
while (operators[(temp)->topOP]!='(')
{
push((temp)->pstfix,pop(operators,(temp)->topOP),(temp)->topPST);
}
char trash=pop(operators,(temp)->topOP);//Unwanted closed bracket
}
}
}
}
}
int choice;
printf("\t\t\tConversion Done successfully. Enter 0 to quite or 1 to return to menu\n\t\t\t");
scanf("%d",&choice);
if(choice) menu();
else exit(0);
}
void acceptEq(list l)
{
system("cls");
char newEq[100];
printf("\t\t\t Enter your equation please. Note that your equation must not exceed the 100 characters length.\n\t\t\t");
scanf("\t\t\t%s",newEq);
position temp=l;
position p=(position)malloc(sizeof (struct node));
while ((temp)->next!=NULL)
{
temp=(temp)->next;
}
(temp)->next=p;
isValid(p);
if ((p)->validity)
{
fillInfix(p,newEq);
convert(p);
}
}
void getResult(list l)
{
system("cls");
position temp=l;
while ((temp)->next != NULL)
{
temp=(temp)->next;
int i=0;
while ((temp)->pstfix[i]!= '\0')
{
if ((temp)->pstfix[i]=='+' || (temp)->pstfix[i]=='-' || (temp)->pstfix[i]=='*' || (temp)->pstfix[i]=='/')
(temp)->result = calculate((temp)->pstfix[i],(temp)->pstfix[i-2],(temp)->pstfix[i-1]);
push((temp)->pstfix,(temp)->result,(temp)->topPST);
printf("\n\t\t\t%c",(temp)->pstfix[i]);
i++;
}
printf("=%f",(temp)->result);
}
}
double calculate (char operation,int op1,int op2)
{
double result;
if (operation=='+') result=op1+op2;
if (operation=='-') result=op1-op2;
if (operation=='*') result=op1*op2;
if (operation=='/') result=op1/op2;
return result;
}
void writeToFile(list l)
{
system("cls");
char fileWName[50];
printf("\n\t\t\tEnter the name of the file you want to print on please\n\t\t\t");
scanf("\t\t\t%s",fileWName);
FILE* resultFile;
resultFile=fopen(fileWName,"w");
position temp=l;
fprintf(resultFile,"Infix Notation:\t\t");
fprintf(resultFile,"Validity:\t\t");
fprintf(resultFile,"Postfix Notation:\t\t");
fprintf(resultFile,"Value:\t\t\n");
while ((temp)->next != NULL)
{
temp=(temp)->next;
int i=0;
while ((temp)->eq[i]!='/0')
{
fprintf(resultFile,"%c",(temp)->eq[i]);
i++;
}
fprintf(resultFile,"\t\t");
i=0;
while ((temp)->pstfix[i]!='/0')
{
fprintf(resultFile,"%c",(temp)->pstfix[i]);
i++;
}
fprintf(resultFile,"\t\t");
if ((temp)->validity == 0) fprintf(resultFile,"INVALID");
else
{
fprintf(resultFile,"VALID\t\t");
fprintf(resultFile,"%f",(temp)->result);
}
}
fclose(resultFile);
int choice;
printf("\t\t\tDATA WRITTEN TO FILE SUCCESSFULLY. Press 1 to return to menu or 0 to quite\n\t\t\t");
scanf("%d",&choice);
if (choice) menu(l);
else exit(0);
}
void showConsole(list l)
{
system("cls");
position temp=l;
printf("Infix Notation:\t\t");
printf("Validity:\t\t");
printf("Postfix Notation:\t\t");
printf("Value:\t\t\n");
while ((temp)->next != NULL)
{
temp=(temp)->next;
int i=0;
while ((temp)->eq[i]!='/0')
{
printf("%c",(temp)->eq[i]);
i++;
}
printf("\t\t");
i=0;
while ((temp)->pstfix[i]!='/0')
{
printf("%c",(temp)->pstfix[i]);
i++;
}
printf("\t\t");
if ((temp)->validity == 0) printf("INVALID");
else
{
printf("VALID\t\t");
printf("%f",(temp)->result);
}
}
int choice;
printf("\t\t\tDATA WRITTEN SUCCESSFULLY. Press 1 to return to menu or 0 to quite\n\t\t\t");
scanf("%d",&choice);
if (choice) menu();
else exit(0);
}
I've already used debugger to find out where my problem is. And now I know that there's a compiling error in this statement:
(l)->next=(position)malloc(sizeof (struct node));
I'm wondering what's wrong with this statement? I'm trying to allocate space for a node in order to be able to create more nodes for each line (equation).
In this case it's easy to see what's wrong: You try to dereference a NULL pointer.
To understand why, you should know that all global variables, like the variable l in your program, are zero-initialized. That basically means that the pointer l is initialized to NULL.
The problem arise because memory for l is not allocated until after you call the menu function. So any function called from menu will have l equal NULL.
There are a few other problems with your code. One is that memory you allocate with malloc is not initialized at all, so for example when you later in the readFile function call isValid with the newly allocated node, and in isValid dereference the temp->next pointer, the value of that next pointer is indeterminate (and in reality will be seemingly random). Accessing uninitialized data like that will lead to undefined behavior. This of course goes for all data inside the structure, not just pointers.
You also don't seem to set temp->validity to non-zero anywhere.

Resources