Having problems displaying structure array content - c

I want to display structure members based on user input, but I don't know if I've stored the input properly.
When I try display all people, it just outputs random numbers.
These are the structures and function prototypes
#define MAX_NAME_LEN 15
#define MAX_NUM_PERSON 4
#define MAX_JOB_LENGTH 20
typedef struct birth_date
{
int month;
int day;
int year;
} person_birth_t;
typedef struct person
{
char pName[MAX_NAME_LEN];
char job[MAX_JOB_LENGTH];
person_birth_t birth_t;
} person_t[MAX_NUM_PERSON];
void print_menu (void);
void scanPerson(person_t p, int);
void displayPeople(person_t p);
This is the main code for the program, a menu is printed asking user to input a number, if a user enters 1 then it prompts them to add a person. Entering 2 displays all people entered.
int main(void)
{
/* TODO */
print_menu();
return 0;
}
void print_menu (void)
{
int choice;
person_t p;
static int index = 0;
int *indexP = NULL;
indexP = &index;
/*Print the menu*/
scanf("%d", &choice);
switch (choice)
{
case 1:
if (index < MAX_NUM_PERSON){
scanPerson(p, index);
++*indexP;
print_menu();
} else {
printf("Can't add more people - memory full \n");
print_menu();
}
break;
case 2:
displayPeople(p);
break;
case 3:
exit(0);
break;
default:
print_menu();
}
}
/*function called when add person is chosen from menu */
void scanFlight(person_t p, int index){
/*printf to enter name*/
scanf(" %s", p[index].pName);
/*printf to enter job*/
scanf("%s", p[index].job);
}
void displayPeople(person_t p){
for(int i = 0; i < MAX_NUM_PERSON; i++){
printf("%s %d-%d-%d %s \n",p[i].pName
,p[i].birth_t.month
,p[i].birth_t.day
,p[i].birth_t.year
,p[i].job);
}
}
I've tried other ways to take input and add it to a struct array, but I'm just not sure how to do it right.

person_t p;
Here, you use the local variable p (in print_menu function), so each recursion, you just print the parameters of the local variable that is not initialized.
To solve it, you can declare p as the global variable.
OT, in scanFlight function, to avoid overflow, you should change the scanf function to:
/*printf to enter name*/
scanf("%14s", p[index].pName);
/*printf to enter job*/
scanf("%20s", p[index].job);
And, rename scanPerson to scanFlight, because i do not see any implementation of scanPerson function in your code. I think it's typo, no ?

None of the methods were working, so instead of trying to figure it out, I scrapped the static index and indexP.
Instead, I initialized p with malloc:
person_t *p= malloc(MAX_NUM_PERSON * sizeof(person_t));
I changed the scan function to accommodate for the change and made index a pointer instead, and I made the display function pass the index.
When I ran it, the output was correct.

Related

String in structure gets deleted

I'm working on the last exercise of the "Think like a computer scientist, C version" book and I have some trouble with one particular point.
The exercise consists of making a small game, where the computer picks a random value between 0 and 20 and then asks me to guess the number.
After that, the computer counts the number of tries I made and, if I get a better score than the previous party, I need to store my name and the number of tries in a structure.
My problem is the following: When I restart the game, the string value, player_name, in the structure gets somehow deleted but player_score is still there.
First, I made a "call by value" function to create the structure and then a tried with a "call by reference" but getting the same results.
I think I tried everything I could with my actual knowledge for now; so, if someone could check my code and give me some tips about what's wrong I would much appreciate it!
//HEADERS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define FALSE 0
#define TRUE 1
//TYPEDEF STRUCTS
typedef struct
{
int player_score;
char *player_name;
} HS_Player;
//FUNCTION PROTOTYPES
int Random_Value(void);
int Get_User_Choice(void);
int Check_Result(int computer, int my_choice);
int Try_Again(int game_result, int computer);
void Player_Infos(HS_Player *player_p, int score);
int Game_Restart(void);
//MAIN
int main(void)
{
int end_game;
int high_score_value = 100;
HS_Player player;
while (end_game != TRUE)
{
int computer_number = Random_Value();
printf("Guess the number between 0 et 20 chosen by the computer.\n");
int your_number = Get_User_Choice();
int result_game = Check_Result(computer_number, your_number);
int tries_to_win = Try_Again(result_game, computer_number);
printf("Number of tries: %i\n", tries_to_win);
if (tries_to_win < high_score_value)
{
Player_Infos(&player, tries_to_win );
high_score_value = player.player_score;
}
printf("Highest score: %i By: %s\n", player.player_score, player.player_name);
printf("\n");
end_game = Game_Restart();
}
return EXIT_SUCCESS;
}
//Random_Value FUNCTION
int Random_Value(void)
{
srand(time(NULL));
int x = rand();
int y = x % 20;
return y;
}
//Get_User_Choice FUNCTION
int Get_User_Choice(void)
{
int success, x;
char ch;
printf("Your Guess:\t");
success = scanf("%i", &x);
while (success != 1)
{
printf("Your input is not a number. Please try again:\t");
while ((ch = getchar()) != '\n' && ch != EOF);
success = scanf("%i", &x);
}
if (x < 0 || x > 20)
{
printf("Your input must be between 0 and 20. Please try again.\n");
Get_User_Choice();
}
return x;
}
//Check_Result FUNCTION
int Check_Result(int computer, int my_choice)
{
int check_result;
if (my_choice < computer)
{
printf("Computer number is larger!\n");
check_result = FALSE;
}
else if (my_choice > computer)
{
printf("Computer number is smaller!\n");
check_result = FALSE;
}
else if (my_choice == computer)
{
printf("It's a Match! You chose the same number than the computer.\n");
printf("\n");
check_result = TRUE;
}
return check_result;
}
//Try_Again FUNCTION
int Try_Again(int game_result, int computer)
{
int tries_befor_success = 1;
while (game_result != TRUE)
{
int your_number = Get_User_Choice();
game_result = Check_Result(computer, your_number);
tries_befor_success++;
}
return tries_befor_success;
}
//Player_Infos FUNCTION
void Player_Infos(HS_Player *player_p, int score)
{
char new_name[80];
printf("Congrats! Your made a new high score.\n");
printf("What's your name ?\t");
scanf("%s", new_name);
printf("\n");
player_p->player_score = score;
player_p->player_name = new_name;
}
//Game_Restart FUNCTION
int Game_Restart(void)
{
int quit_value;
printf("Quit Game ?\n");
printf("Press 'y' to quit or any other keys to continue.\n");
fflush(stdin);
char quit_game = getchar();
printf("\n");
if (quit_game == 'y')
{
quit_value = TRUE;
}
else
{
quit_value = FALSE;
}
return quit_value;
}
The problem is that, in your Player_Infos function, you are assigning the address of a local array to the char* player_name pointer member of the passed structure. When that function ends, the local array it used will be deleted and the pointer in the structure will be invalid. (In the case of the player_score, you don't have that problem, because the given value is copied to the structure member.)
There are several ways around this; one would be to use the strdup() function to make a copy of the local char new_name[80]; array – but that is really overkill, and you would need to manage (i.e. free()) that allocated string whenever you make a modification.
A simpler way is to make the player_name member an actual array of char and then use strcpy() to copy the local array into that member.
Better, still, with the player_name member defined as char [80], you can read directly into that (in the function), and avoid the local array completely:
typedef struct
{
int player_score;
char player_name[80];
} HS_Player;
//...
void Player_Infos(HS_Player *player_p, int score)
{
printf("Congrats! Your made a new high score.\n");
printf("What's your name ?\t");
// Read directly. Limit input to 79 chars (allowing room for null terminator).
scanf("%79s", player_p->player_name);
printf("\n");
player_p->player_score = score;
}
Also, just as a "style" tip, you may want to change the member names to just score and name, as the "player" part is implied by the structure type-name itself.
This issue you are having is that you are associating the player name pointer to a variable that goes out of scope when you leave the "player_Infos" function. What you probably would want to do is define the name as a character array in your structure and then use the "strcpy" call in your function instead. Following is a couple of code snippets illustrating that point.
//TYPEDEF STRUCTS
typedef struct
{
int player_score;
char player_name[80];
} HS_Player;
Then, in your function, use the "strcpy" call.
//Player_Infos FUNCTION
void Player_Infos(HS_Player *player_p, int score)
{
char new_name[80];
printf("Congrats! Your made a new high score.\n");
printf("What's your name ?\t");
scanf("%s", new_name);
printf("\n");
player_p->player_score = score;
strcpy(player_p->player_name, new_name);
//player_p->player_name = new_name;
}
When I tested that out, I got a name to appear in the terminal output.
Computer number is smaller!
Your Guess: 4
It's a Match! You chose the same number than the computer.
Number of tries: 8
Highest score: 4 By: Craig
FYI, you will need to include the "string.h" file.
Give that a try.
Name Update
The reason your player.player_name is not getting updated is because you can't assign a string this way in C. When doing player_p->player_name = new_name; you're actually saving in player_p->player_name the memory address of new_name.
Instead, what you want to achieve, is to copy each character of new_name to player_p->player_name and in order to achieve this, you have to change the type of prlayer_name field from char* player_name to char player_name[80], then assign it using, for example, strcpy():
#include <string.h>
// [...]
//TYPEDEF STRUCTS
typedef struct
{
unsigned int player_score;
char player_name[80];
} HS_Player;
// [...]
//Player_Infos FUNCTION
void Player_Infos(HS_Player *player_p, int score)
{
char new_name[80];
printf("Congrats! Your made a new high score.\n");
printf("What's your name ?\t");
scanf("%s", new_name);
printf("\n");
player_p->player_score = score;
strcpy(player_p->player_name, new_name);
}
Data Persistence
To make data (players info) persistent over multiple runs, you have to save the content of the struct to a file.
Example
int Save_Score(char* filename, HS_Player* player)
{
FILE* file = fopen(filename, "w");
if (file == NULL)
{
fprintf(stderr, "\nAn error occurred while opening the file\n");
return -1;
}
if (fprintf(file, "%d %s", player->player_score, player->player_name) < 0)
return -1;
fclose(file);
return 0;
}
int Load_Score(char* filename, HS_Player* player)
{
FILE* file = fopen(filename, "r");
if (file == NULL)
{
fprintf(stderr, "\nAn error occurred while opening the file\n");
return -1;
}
if (fscanf(file, "%d %79s", &player->player_score, player->player_name) < 0)
return -1;
fclose(file);
return 0;
}

Trying to print a struct element but getting blank. - C

I have a struct person that has the following elements, defined in data.h
typedef struct person{
char firstName[20];
char familyName[20];
char telephoneNum[20];
int type; // 0 = student / 1 = employee;
}newPerson;
I created an array of person[MAX_PERSONS] that is initialized in my menu() function. I then have an addFirstName(newPerson pers) function. However when I try to test print format using my printFormat(newPerson pers)function, I get blank, instead of the inputted name.
I have included the menu(), addFirstname(newPerson pers), and printFormat(newPerson pers) function below. I was wondering if anyone could tell me the reason for this. Any help or pointers would be appreciated. Thank you in advance.
int menu(){
int num = 0;
newPerson person[MAX_PERSONS];
int option; // for user input for menu
printf("\n\tPlease choose one of the following options to continue (0-9): ");
scanf("%d", &option );
printf("\n\tYou selected %d\n", option);
if (option == 0){ //program will close
printf("\tProgram will now close.\n");
exit(1);
}
if (option == 1){ //program will ask for name input
addRecord(person[num]);
printFormat(person[num]);
char choice[0];
printf("\n\t\tWould you like to enter another record? (y/n): ");
scanf("%s", choice);
if (choice[0] == 'y'){
num++;
addRecord(person[num]);
}
if (choice[0] == 'n'){
num++;
mainMenu();
}
/*
IF YES, THEN NUM++
THEN RUN ADDRECORD(PERSONNUM) AGAIN.
IF NO, THEN RETURN TO MAIN MENU.
PRINTMENU
THEN RUN MENU AGAIN
*/
}
printf("\n\tNot a valid option, please try again // THE END OF MENU FUNCTION\n");
return 0;
}
void addFirstName(newPerson pers){
char firstName[20];
printf("\n\tEnter first Name: ");
scanf("%20s", firstName);
strcpy(pers.firstName, firstName);
printf("\n\tThe name entered is %s", pers.firstName);
}
void printFormat(newPerson pers){
printf("\t\tThe name is %s", pers.firstName);
}
It's because you pass the structure to addFirstName by value meaning that the function receives a copy of the structure. And changing a copy will of course not change the original.
While C does not support passing arguments by reference, it can be emulated using pointers. So change the addFirstName function to receive a pointer to the structure as its argument.
Your big problem is that you are passing structures by value instead of by pointers. This result in that you change copies of original objects inside your function addFirstName and not the original object. You should declare it as:
void addFirstName( newPerson* pers);
void printFormat( newPerson* pers);
Example:
#include <stdio.h>
void call_by_value(int x) {
printf("Inside call_by_value x = %d before adding 10.\n", x);
x += 10;
printf("Inside call_by_value x = %d after adding 10.\n", x);
}
int main() {
int a=10;
printf("a = %d before function call_by_value.\n", a);
call_by_value(a);
printf("a = %d after function call_by_value.\n", a);
return 0;
}
this will produce:
a = 10 before function call_by_value.
Inside call_by_value x = 10 before adding 10.
Inside call_by_value x = 20 after adding 10.
a = 10 after function call_by_value.

When I run this program, after entering a name, I get a segmentation fault. How can I fix this to make it work properly?

Restauraunt.c
This program allows you to create a restaurant menu, stores it in a file, and then rates each item on the menu. It uses file functions to output everything into a file that can then be viewed through almost any program. When the program gets to the line in nametofile() 'fprintf(restauraunt, "%s Restauraunt\n\n",name);' the program gives a segmentation fault. I do not know why it is doing this, I have attempted several different methods of debugging, but none have worked. If you have any suggestions, please comment them below.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
FILE *restauraunt;
char name[20];
char item[20];
char price[20];
int count=0;
void nametofile();
void rate();
void itemtofile();
void counter();
void renamefile();
int main()
{
int i,j;
int num;
printf("Restauraunt Creator\n\n");
printf("Enter the name of your restauraunt:\n");
scanf("%s",&name);
nametofile();
printf("\nEnter the number of items to be included in your menu:\n");
scanf("%d", &num);
/* Cycles through each entry to the menu */
for(i=0;i<num;i++)
{
counter();
fpurge(stdin);
printf("\nPlease enter the name of item number %d:\n",count);
scanf("%s", &item);
printf("\nPlease enter the price of item number %d:\n",count);
scanf("%s", &price);
itemtofile();
rate();
}
renamefile();
}
/*void nametofile()
{
restauraunt = fopen("restauraunt","w");
fprintf(restauraunt, "%s Restauraunt\n\n",name);
fclose(restauraunt);
}*/
/* The function that sends the restaurant name to the file */
void nametofile()
{
int i;
i = strlen(name);
name[i+1] = '\0';
restauraunt = fopen("restauraunt","w");
/* the line that gives a segmentation fault */
fprintf(restauraunt, "%s Restauraunt\n\n",name);
fclose(restauraunt);
}
/* rates each menu item */
void rate()
{
int rating;
srandom((unsigned)time(NULL));
restauraunt = fopen("restauraunt", "a");
rating = random() % 5 + 1;
fprintf(restauraunt,"Your food's rating was:\t%d stars!",rating);
switch(rating)
{
case 1:
{
fprintf(restauraunt," Here's why: Your food was not very good tasting and the price was ridiculously high.\n");
break;
}
case 2:
{
fprintf(restauraunt," Here's why: Your food was mildly good tasting and the price was too high.\n");
break;
}
case 3:
{
fprintf(restauraunt," Here's why: Your food was somewhat good tasting and the price was fair.\n");
break;
}
case 4:
{
fprintf(restauraunt," Here's why: Your food was quite good tasting and the price was very nice.\n");
break;
}
case 5:
{
fprintf(restauraunt," Here's why: Your food was very delicious and the price was amazingly low.\n");
break;
}
}
}
/* sends each item to the file */
void itemtofile()
{
restauraunt = fopen("restauraunt","a");
fprintf(restauraunt, "%s: $%s\nRating:",item,price);
fclose(restauraunt);
}
/* counts up one each time function is called */
void counter()
{
count += 1;
}
/* renames the file at the end */
void renamefile()
{
int x,y;
char bridge[] = { "menu" };
name[0] = tolower(name[0]);
x = strcat(name,bridge);
y = rename("restauraunt",name);
}
name is a char array. When you pass it to scanf or other functions, it decays to a pointer, so you do not need the & operator:
scanf("%19s", name);
When you read strings with scanf, it is a good idea to pass the size limit: this lets you avoid buffer overruns. Since name is declared as char[20], you pass 19, because one more char needs to be reserved for the null terminator.

How to approach and optimize code in C

I am new to C and very much interested in knowing how to approach any problem which has more than 3 or 4 functions, I always look at the output required and manipulate my code calling functions inside other functions and getting the required output.
Below is my logic for finding a students record through his Id first & then Username.
This code according to my professor has an excessive logic and is lacking in many ways, if someone could assist me in how should I approach any problem in C or in any other language it would be of great help for me as a beginner and yes I do write pseudo code first.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
int id; //Assuming student id to be unique
int age;
char *userName; //Assuming student userName to be unique
char *dept;
}student; // Alias "student" created for struct
student* createstruct(); // All function prototype declared
student* createArray();
void addstruct(student* s2);
void searchChar(student* s2,int num);
void searchInt(student* s2,int num);
student* createstruct() // function createStruct() to malloc data of struct student.
{
student *s;
s = (student*)malloc(sizeof(student));
s->userName = (char*)malloc(sizeof(char)*32);
s->dept = (char*)malloc(sizeof(char)*32);
printf("please enter id ");
scanf("%d",&s->id);
printf("please enter age ");
scanf("%d",&s->age);
printf("please enter userName ");
scanf("%31s",s->userName);
printf("please enter department ");
scanf("%31s",s->dept);
printf("\n");
return s;
}
student* createArray()
{
student *arr; //declaration of arr poiter, type struct student
arr = (student*)malloc(sizeof(student)*10); // memory allocated for a size of 10
return arr;
}
void addstruct(student *s2) // function for adding data to the structures in array
{
int i,num;
student* s1;
printf("please enter the number of records to add:");
scanf("%d",&num);
printf("\n");
if(num>0 && num<11)
{
for(i=0;i<num;i++) // if user want to enter 5 records loop will only run 5 times
{
s1 = createstruct();
s2[i].id = s1->id; // traversing each element of array and filling in struct data
s2[i].age = s1->age;
s2[i].userName = s1->userName;
s2[i].dept= s1->dept;
}
}
else if(num>10) // if user enters more than 10
{
for(i=0;i<10;i++) // loop will still run only 10 times
{
s1 = createstruct();
s2[i].id = s1->id;
s2[i].age = s1->age;
s2[i].userName = s1->userName;
s2[i].dept = s1->dept;
}
printf("Array is full"); // Array is full after taking 10 records
printf("\n");
}
searchInt(s2,num); // Calling searchInt() function to search for an integer in records
searchChar(s2,num); // Calling searchChar() function to search for a string in records
free(s1);
free(s2);
}
void searchChar(student* s2,int num) // function for searching a string in records of structure
{
char *c;
int i;
c = (char*)malloc(sizeof(char)*32);
printf("please enter userName to search ");
scanf("%31s",c);
printf("\n");
for (i=0;i<num;i++) //num is the number of struct records entered by user
{
if ((strcmp(s2[i].userName,c)==0)) //using strcmp for comparing strings
{
printf("struct variables are %d, %d, %s, %s\n", s2[i].id,s2[i].age,s2[i].userName,s2[i].dept);
break;
}
else if(i == num-1)
{
printf("nothing in userName matches: <%s>\n",c);
break;
}
}
}
void searchInt(student* s2,int num) //searchs for an integer and prints the entire structure
{
int i,z;
printf("please enter id to search ");
scanf("%d",&z);
printf("\n");
for (i=0;i<num;i++)
{
if (s2[i].id == z)
{
printf("struct variables are %d, %d, %s, %s\n\n", s2[i].id,s2[i].age,s2[i].userName,s2[i].dept);
break;
}
else if(i == num-1)
{
printf("nothing in id matches: <%d>\n\n",z);
break;
}
}
}
int main(void)
{
student *s2;
s2 = createArray();
addstruct(s2);
return 0;
}
I'm not going to go into optimizing, because if you wanted better theoretical performance you would probably go with different data structures, such as ordered arrays/lists, trees, hash tables or some kind of indexing... None of that is relevant in this case, because you have a simple program dealing with a small amount of data.
But I am going to tell you about the "excessive logic" your professor mentioned, taking your searchInt function as an example:
for (i=0;i<num;i++)
{
if (s2[i].id == z)
{
printf("struct variables are %d, %d, %s, %s\n\n", s2[i].id,s2[i].age,s2[i].userName,s2[i].dept);
break;
}
else if(i == num-1)
{
printf("nothing in id matches: <%d>\n\n",z);
break;
}
}
The thing here is that every time around the loop you're testing to see if you're at the last element in the loop. But the loop already does that. So you're doing it twice, and to make it worse, you're doing a subtraction (which may or may not be optimized into a register by the compiler).
What you would normally do is something like this:
int i;
student *s = NULL;
for( i = 0; i < num; i++ )
{
if( s2[i].id == z ) {
s = &s2[i];
break;
}
}
if( s != NULL ) {
printf( "struct variables are %d, %d, %s, %s\n\n",
s->id, s->age, s->userName, s->dept );
} else {
printf("nothing in id matches: <%d>\n\n",z);
}
See that you only need to have some way of knowing that the loop found something. You wait for the loop to finish before you test whether it found something.
In this case I used a pointer to indicate success, because I could then use the pointer to access the relevant record without having to index back into the array and clutter the code. You won't always use pointers.
Sometimes you set a flag, sometimes you store the array index, sometimes you just return from the function (and if the loop falls through you know it didn't find anything).
Programming is about making sensible choices for the problem you are solving. Only optimize when you need to, don't over-complicate a problem, and always try to write code that is easy to read/understand.

Switch-Case Operator -- C

Is there a way to store user inputs in switch case from one operation and use it across switch operations at run-time.
Example: If its a software for a Bank and I want to take information from the user and validate if his a/c number is correct and also check if he has enough bank balance to withdraw money.
I need to know how to store the value of one operation,so that I could use it for further ops.
switch(ops)
{
char ac_no;
long amt,amt2,init_dep;
char name,ac_allocated;
case OpenAC:
{
printf("1.Name:\n");
scanf("%s",&name);
printf("2.A/Cno_allocated:\n");
scanf("%s",&ac_allocated);
printf("3.Initial deposit:\n");
scanf("%d",&init_dep);
break;
}
case Deposit:
{
printf("Enter the a/c number: ");
scanf("%s",&ac_no);
printf("Amount:Rs. ");
scanf("%ld",&amt);
break;
}
case Withdraw:
{
printf("Enter the a/c number: ");
scanf("%s",&ac_no);
printf("Amount:Rs. ");
scanf("%ld",&amt2);
{printf("Cannot withdraw.Rs.500 minimum balance mandatory.\n");}
break;
}
return ops;
}
I also tried declaring variables in the switch(ops) to store the value in them(like in the following case to validate the a/c number in the next step but it doesn't help.)
Edited code:
`
char ac_no;
long amt,amt2,init_dep,dep1;
char name,ac_allocated,ac1;
case OpenAC:
{
printf("1.Name:\n");
scanf("%s",&name);
printf("2.A/Cno_allocated:\n");
scanf("%s",&ac_allocated);
ac_allocated = ac1;
printf("3.Initial deposit:\n");
scanf("%d",&init_dep);
init_dep = dep1;
//break;
}
case Deposit:
{
printf("Enter the a/c number: ");
scanf("%s",&ac_no);
if(ac_no == ac1)
{
printf("Amount:Rs. ");
scanf("%ld",&amt);
}
break;
`
Why not declare your variables outside the switch. You could even put braces around the switch to prevent the variables from leaking to the surrounding function, like this:
// code from the surrounding function
{
char ac_no;
long amt,amt2,init_dep;
char name,ac_allocated;
switch(ops)
{
case OpenAC:
...
}
} // end of block
I'm not sure I understand your problem, but if you declare something inside the curly brackets of the switch statement, it will be out of scope when you hit the ending curly bracket and not usable the next time the switch statement is encountered.
First issue: you're using the wrong type for ac_no, name, ac_allocated, and ac1. You're obviously wanting to store strings at these locations, so instead of a plain char, you need to declare arrays of char:
char ac_no[AC_NO_SIZE];
char name[NAME_SIZE];
char ac_allocated[AC_ALLOCATED_SIZE];
char ac1[AC1_SIZE];
where each *_SIZE is large enough to hold your input data plus 1 extra character for the 0 terminator. IOW, if your account numbers are at most 10 characters long, AC_NO_SIZE needs to be 11.
Second issue: do not declare variables at the head of a switch statement; any initializations will be skipped.
Third issue: auto variables declared inside a specific scope will not be available outside of that scope; they will cease to exist when that scope exits. None of the variables you declare will be available outside of the switch statement.
Fourth issue: if this switch operation is inside of a function, and you want to preserve these values between function calls, you can do one of three things:
Declare these items at file scope, outside of any function (not recommended):
char ac_no[AC_NO_SIZE];
char name[NAME_SIZE];
char ac_allocated[AC_ALLOCATED_SIZE];
char ac1[AC1_SIZE];
long amt, amt2, init_dep;
void foo()
{
int ops;
...
ops = bar(ops);
...
}
int bar(int ops)
{
switch(ops)
{
case OpenAC:
printf("Name: ");
fflush(stdout);
scanf("%s", name); // note no &; true for all char [] types
printf("A/C no allocated: ");
fflush(stdout);
scanf("%s", ac_allocated);
printf("Initial deposit: ");
fflush(stdout);
scanf("%ld", &init_dep);
...
}
return ops;
...
Declare these items as `static` in the function (slightly less recommended); they will not be visible outside of the function, but their value will be retained between function calls:
int bar(int ops)
{
static char ac_no[AC_NO_SIZE];
static char name[NAME_SIZE];
static char ac_allocated[AC_ALLOCATED_SIZE];
static char ac1[AC1_SIZE];
static long amt, amt2, init_dep;
switch(ops)
{
case OpenAC:
printf("Name: ");
fflush(stdout);
scanf("%s", name);
printf("A/C no allocated: ");
fflush(stdout);
scanf("%s", ac_allocated);
printf("Initial deposit: ");
fflush(stdout);
scanf("%ld", &init_dep);
...
}
return ops;
}
Declare these items in the calling function and pass them as parameters to this function (recommended):
int foo(int ops,
char *ac_no,
char *name,
char *ac_allocated,
char *ac1,
long *amt, // Since these values are being modified in the function,
long *amt2, // we must pass pointers to them, otherwise the changes
long *init_dep) // will not be reflected in the calling function
{
switch(ops)
{
case OpenAC:
printf("Name: ");
fflush(stdout);
scanf("%s", name); // no & before name; same is true for rest of parameters
printf("A/C no allocated: ");
fflush(stdout);
scanf("%s", ac_allocated);
printf("Initial deposit: ");
fflush(stdout);
scanf("%ld", init_dep); // no & before init_dep since it's already a pointer
...
All of this assumes I'm understanding your problem correctly.
Maybe you should use structure to hold account data and functions to make it readable and maintainable.
struct account_s { /* Fields borrowed to #John Bode */
char ac_no[AC_NO_SIZE];
char name[NAME_SIZE];
char ac_allocated[AC_ALLOCATED_SIZE];
char ac1[AC1_SIZE];
long amt, amt2, init_dep;
};
int openAC(struct account_s *account);
to be continued... :)

Resources