C structure type variable declaration - arrays

I have written a code for a ticket reservation halfway and I'm doubtful about the way i have used structures and arrays in my code. This code is not formatted properly because I am trying to see if this method of declaring "Bill" type variable will work or is this wrong?
the code gets compiled and runs successfully but I am doubtful whether my method is correct. Can anyone help? I just want to know whether the way I have declared structure type variables and used it is correct?Especially the last printf statement where I calculate the Amount.
#include<stdio.h>
#include<string.h>
#define SIZE 3
typedef struct
{
int billno;
char name[20];
char cat[20];
int type;
int range[3];
int tickets;
int class[3];
float price;
}Bill;
int main()
{
Bill array[3];
Bill d;
int input;
array[0].billno=6434;
strcpy(array[0].name,"Nimal");
strcpy(array[0].cat,"General");
array[0].type=1;
array[0].range[0]= 250;
array[0].range[1]= 0;
array[0].range[2]= 0;
array[0].price = 200;
array[1].billno=6065;
strcpy(array[1].name,"Kamal");
strcpy(array[1].cat,"Industrial");
array[1].type=2;
array[1].range[0]=622;
array[1].range[1]=1999;
array[1].range[2]=102;
array[1].price =125.60;
array[2].billno=7067;
strcpy(array[2].name,"Gayani");
strcpy(array[2].cat,"General");
array[2].type=2;
array[2].range[0]=220;
array[2].range[1]=350;
array[2].range[2]=10;
array[2].price = 86.90;
printf("****Main Menu****");
printf("1.Reserve a ticket:");
scanf("%d",&input);
if(input == 1)
{
printf("Enter your name: ");
scanf("%s", d.name);
printf("Enter the number of tickets you want");
scanf("%d",&d.tickets);
printf("Enter the number of tickets from first class");
scanf("%d",&d.class[0]);
printf("Enter the number of tcikets from second class");
scanf("%d",&d.class[1]);
printf("Enter the number of tickets from third class");
scanf("%d",&d.class[2]);
}
printf("\nReserve a ticket");
printf("\nName : %s",d.name);
printf("\nTickets from first class : %d",d.class[0]);
printf("Tickets from second class : %d\n",d.class[1]);
printf("Tickets from third class : %d\n",d.class[2]);
printf("\nConfirm the order? press Y if yes : ");
printf("Amount = %.2f ",d.class[0]*array[0].price+d.class[1]*array[1].price+d.class[2]*array[2].price);
return 0;
}

Related

What this error mean : expression must have pointer to object type but it has type struct add_stock in c

#include <stdio.h>
int i, n;
struct add_stock
{
char fullname[30];
int stocks;
char com_name[30];
int shares;
float price;
float total;
int totalmoney;
} add;
int main()
{
printf("Enter full name : ");
scanf(" %[^\n]s", add.fullname);
printf("Enter the no. of stocks you want to purchased : ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter the name of the company : ");
scanf(" %[^\n]s", add[i].com_name);
printf("Enter the no. of shares you want to purchased : ");
scanf("%d", &add[i].shares);
printf("Enter the price of each share : ");
scanf("%f", &add[i].price);
add.total = add.shares * add.price;
printf("Toatl money invested in this stock : ");
scanf("%f", &add[i].total);
}
printf("Total money invested : ");
scanf("%d", add.totalmoney);
return 0;
}
In question it's add_stock , not add stock , i write like this becoz it's not accepting question.
So, i get error for "add" saying subscripted value is neither array nor pointer nor vector.
To declare an array of strucuture, you need to define the variable as below,
struct add_stock
{
char fullname[30];
int stocks;
char com_name[30];
int shares;
float price;
float total;
int totalmoney;
} add[20];
this makes the add as an array of add_stock elements.
then you can access it as, add[0].total, add[1].price and so on.
If you want to declare an array that need to be having dynamic number of elements, you can do so as below.
struct add_stock* arStock;
//allocate memory to hold 10 elements
arStock = (add_stock*)malloc( 10 * sizeof(struct add_stock));
arStock[0]->total=10; //access it with ->, instead of .

How to pass each element of array of structs into a function?

I am trying to create a simple c program having an array of structures and I am passing each element of the array into a function and then trying to display it below is my code.
#include<stdio.h>
#include<string.h>
struct students{
char name[50];
int marks;
}st[10];
int size;
int addStudent(struct students st,char sname[], int marks){
static int count = 0;
strncpy(st.name,sname,strlen(sname));
st.marks = marks;
count++;
return count;
}
void showStudents(int size){
int i;
printf("Total number of students : %d\n",size);
for(i=0;i<size;i++){
printf("Student Name : %s\nMarks : %d\n",st[i].name,st[i].marks);
}
}
int main(){
int n, marks, i;
char name[50];
printf("Enter the total number of students : ");
scanf("%d",&n);
getchar();
for(i=0;i<n;i++){
printf("Enter the name of the Student : ");
fgets(name,50,stdin);
printf("Enter the marks of the student : ");
scanf("%d",&marks);
getchar();
size = addStudent(st[i], name, marks);
}
showStudents(size);
return 0;
}
and I am getting the following output
Enter the total number of students : 2
Enter the name of the Student : shibli
Enter the marks of the student : 23
Enter the name of the Student : max
Enter the marks of the student : 45
Total number of students : 2
Student Name :
Marks : 0
Student Name :
Marks : 0
Instead of getting the names and the marks I am getting no values can anyone help me what I am doing wrong with my code.
When passing a struct to a function, the function actually copies the struct to the input struct parameter and works on it. So the function addStudent did not work on your global array item but on a local copy.
You should pass a pointer to the struct item to the function and work on that. The code then looks like this:
int addStudent(struct students *st,char sname[], int marks){
static int count = 0;
strncpy(st->name,sname,strlen(sname)+1);
st->marks = marks;
count++;
return count;
}
and the call to the function addStudent looks like this:
size = addStudent(&st[i], name, marks);
In general the code can have other improvements like not using global variables, and static counters, but this is outside the scope of your question.
there is another issue here, using strncpy for copying strlen of string, does not end the string with null. So you should use strlen+1 to copy also the null termination, or simply use snprintf which adds null termination at end of string

Average generates a negative decimal number

I created a function called average that will calculate the average age. How ever it is generating a strange negative decimal point.It was working fine until I put the strcmp function to people who have enter Texas. Example ages: 20 50 20 30 & 40 generate The average age is -243454739.00.
Can someone point me in the right direction, Thanks.
#include <stdio.h>
#include <string.h>
int main()
{
//function decleration
float average ( int A, int n);
//int deleceration
char names, states, statedata[100], namedata[100];
int agedata[100], age, count = 0, A, n, avg;
float a;
//Get User Input
printf("Enter Number of family members being enter into program \n");
scanf("%d", &n);
//Name Loop
for (names=0; names<n; ++names)
{
printf("Enter Family members name:\n");
scanf("%s", &namedata);
//Age Loop
for (age=0; age<1; ++age)
{
printf("Enter family members age:\n");
scanf("%d", &agedata[age]);
A +=agedata[age];
count= count + 1;
//State Loop
for (states=0; states<1; ++states)
{
printf("Enter Family members state:\n");
scanf("%s", &statedata);
//strcmp function for state name "Texas" Selection
if (strcmp(statedata,"texas")==0)
{
printf("Family members who live in texas\n");
printf("%s\n", namedata);
}
}
}
}
// Average function call
a = average(A, n);
printf("The average age is %.2f\n", a);
return 0;
}
//A declarator
float average( int A, int n){
float average;
average = A / n;
return average;
}
Initialize A to 0 in main(). Uninitialized local variables have indeterminate values in C.
Other issues:
1)
scanf("%s", &namedata);
scanf("%s", &statedata);
Shoud be
scanf("%s", namedata);
scanf("%s", statedata);
Because scanf() expects a char* when for format specifier %s whereas you are passing char(*)[100].
2)
All the values of ages are using type int. So the having the function average() return a float is still going to give an int result.
Change the type A (in main()) and the function parameter A (in average()) to float.
3)
Your inners are running 0..1 i.e. only once. So you don't really need those loops.

C store values in an array

My program reads the following data: Date, Distance and Time.
So for example an input would look like:
Date: 10.10.2013
Distance (m): 500
Time (HH:MM:SS): 01:20:05
I want to store all this information in an array. The problem is that I want the user to input date, distance and time several times and the program has to save all the data in an array.
I can't store it like this, because then how would I know which index is the date index? And how should I store the time? I can't store it with :.
arr[0] = 10.10.2013
arr[1] = 500
arr[2] = 012005
arr[3] = 22.10.2013
arr[4] = 200
arr[5] = 000510
You can make a struct:
struct Data{
Date date;
Distance distance;
Time time;
}
Then declare an array of Data and use it like that:
Data arr[5];
arr[0].date = //some date;
arr[0].distane =//some distance
arr[0].time=//some time
Because the type of data you will need to store, it needs type char, so it can be stored in strings. (i.e. "10.10.2013")
First, Define a struct PARAM:
typedef struct {
char date[20];
char distance[20];
char time[20];
} PARAM;
use PARAM to create an array of your struct:
PARAM param[20];
Now, you can use it like this for example:
int main(void)
{
strcpy(param[0].date, "10.10.2013");
strcpy(param[0].time, "05:02:10");
strcpy(param[0].distance, "500");
//and so on for all the struct array elements, 0 through 20
return 0;
}
Or, better yet, using printf() and scanf() statements as necessary, you can prompt the user for input in a loop, and store in your struct array:
int main(void)
{
int i;
for(i=0;i<20;i++)
{
printf("enter date %d:", i+1);
scanf("%s", param[i].date);
printf("enter distance %d:", i+1);
scanf("%s", param[i].distance);
printf("enter time %d:", i+1);
scanf("%s", param[i].time);
}
return 0;
}
EDIT Regarding question in comment Therefore I guess its best to store them in date.day, date.month and date.year. Right? That approach would work, and I include it below, but it is a little more tedious to enter data that way. I included a second example below that might improve both, entering data, and storing data.
So, Per your comment, two ways jump to mind:
ONE, create struct members that contain the discrete members of time and date as integers: i.e.
typedef struct {
int day;
int month;
int year;
int hour;
int minute;
int second;
}TIMEDATE;
Use this struct as a member of the PARAM struct;
typedef struct {
int distance;
TIMEDATE timedate;
}PARAM;
PARAM param[20];
Now, just modify and expand the example of the last main() function to include scanning in values for the new struct members. This will be more tedious for the person using your program, but will allow you to keep all the input values as numbers as you have indicated.
//Note the changes in scanf format specifiers for int, "%d":
// in all the statements
int main(void)
{
int i;
for(i=0;i<20;i++)
{
printf("enter date %d:", i+1);
scanf("%d", &param[i].timedate.day);
printf("enter time %d:", i+1);
scanf("%d", &param[i].timedate.month);
printf("enter time %d:", i+1);
scanf("%d", &param[i].timedate.year);
printf("enter time %d:", i+1);
scanf("%d", &param[i].timedate.hour);
printf("enter time %d:", i+1);
scanf("%d", &param[i].timedate.minute);
printf("enter time %d:", i+1);
scanf("%d", &param[i].timedate.second);
printf("enter time %d:", i+1);
scanf("%d", &param[i].distance);
}
return 0;
}
Two, modify the first approach to include using strings AND integers, all in the same struct. This will make it easier for the user user to enter time and date information, and possible for you to manipulate the data easier. And a bonus, it will demonstrate how to parse the user input string data into integer data.
typedef struct {
char date[20];//keep as char
char time[20];//keep as char
int distance; //changed to int
TIMEDATE timedate;//container for in data
} PARAM;
//use PARAM to create an array of your struct:
PARAM param[20], *pParam; //create a pointer to pass
int GetIntData(PARAM *p, int index);//prototype for new function
//Note the changes in scanf format specifiers for int, "%d":
// in all the statements
int main(void)
{
int i, loops;
pParam = &param[0]; //initialize pointer to struct
printf("How many sets of data would you like to enter? :");
scanf("%d", &loops);
for(i=0;i<loops;i++)
{
printf("enter date (eg:MM.DD.YYYY): %d:", i+1);
scanf("%s", pParam[i].date);
printf("enter time (eg HH:MM:SS): %d:", i+1);
scanf("%s", pParam[i].time);
printf("enter distance %d:", i+1);
scanf("%d", &pParam[i].distance);
GetIntData(pParam, i);
}
return 0;
}
//reads string members into integer members
int GetIntData(PARAM *p, int index)
{
char *buf=0;
if(strstr(p[index].date, ".")==NULL) return -1;
p[index].timedate.month = atoi(strtok(p[index].date, "."));
p[index].timedate.day = atoi(strtok(NULL, "."));
p[index].timedate.year = atoi(strtok(NULL, "."));
if(strstr(p[index].time, ":")==NULL) return -1;
buf=0;
p[index].timedate.hour = atoi(strtok(p[index].time, ":"));
p[index].timedate.minute = atoi(strtok(NULL, ":"));
p[index].timedate.second = atoi(strtok(NULL, ":"));
return 0;
}

Expression must have class type error

I'm working on a homework assignment and I've hit a brick wall. I think I have all of the code that I need, I just need to get the program to compile. The object of the assignment is
Create a structure to hold student names and averages. The structure should contain a first name, last name and an integer grade average.
Then:
Write a program that will do the following:
1.) Create an array of pointers to these student structures.
2.) Prompt the user for names and averages.
3.) After you get the student’s information use malloc to provide the memory to store the information.
4.) Place the address of the student, returned by malloc, into the pointer array.
5.) AFTER the user indicates there are no more students:
Search the data entered and find the highest and lowest grade
average.
a)Print the name and grade for the highest grade
b)Print the name and grade for the lowest grade
c)Print the average of all grades entered
Here is my code:
#include "stdafx.h"
#include <string.h>
#include <stdlib.h>
#define SIZE 25
int enterStudents (int ePointArray[SIZE]);
void searchData (int *sPointArray, int *sHigh, int *sLow);
int calculateAvg (int, int *avgPointArray);
void printData (int, int *pHigh, int *pLow);
struct student
{
char firstName[20];
char lastName[20];
int average;
};
int main()
{
int pointArray[SIZE], high[3], low[3];
int i = 0, studentCounter, avgGrade;
for (i = 0; i < SIZE; i++)
pointArray[i] = 0;
studentCounter = enterStudents(pointArray);
searchData(pointArray, high, low);
avgGrade = calculateAvg(studentCounter, pointArray);
printData(avgGrade, high, low);
return 0;
}
int enterStudents (int ePointArray[SIZE])
{
char tempFname[20], tempLname[20], yesNo[2] = "y";
int tempAvg, counter = 0;
int *studPtr;
struct student aStud={"\0", "\0", 0};
while( counter < SIZE && strcmp(yesNo, "y")==0)
{
printf(" Enter first name: ");
scanf("%s", tempFname);
printf(" Enter last name: ");
scanf("%s", tempLname);
printf(" Enter grade average:");
scanf("%d", tempAvg);
strcpy(aStud.firstName, tempFname);
strcpy(aStud.lastName, tempLname);
aStud.average = tempAvg;
studPtr = malloc(sizeof(struct student));
ePointArray[counter] = *studPtr;
counter++;
printf("/n");
printf(" Do you have more students? yes or no:");
scanf("%s", yesNo);
}
return counter;
}
void searchData (int sPointArray[SIZE], int sHigh[3], int sLow[3])
{
int searchCounter = 0;
while( searchCounter = 0)
{
if( *sPointArray[searchCounter].average > *sPointArray[searchCounter+1].average)
{
sHigh[0] = &sPointArray[searchCounter].firstName;
sHigh[1] = &sPointArray[searchCounter].lastName;
sHigh[2] = &sPointArray[searchCounter].average;
}
if( *sPointArray[searchCounter].average < *sPointArray[searchCounter+1].average)
{
sLow[0] = &sPointArray[searchCounter].firstName;
sLow[1] = &sPointArray[searchCounter].lastName;
sLow[3] = &sPointArray[searchCounter].average;
}
searchCounter++;
}
}
int calculateAvg( int totalStudents, int avgPointArray[SIZE])
{
int sum = 0;
int avgCounter;
double overallAvg;
for( avgCounter = 0; avgCounter < totalStudents; avgCounter++)
sum = sum + *avgPointArray[avgCounter].average;
overallAvg = sum/totalStudents;
return overallAvg;
}
void printData (int pAverage, int pHigh[3], int pLow[3])
{
printf(" Highest Grade: %s %s %d", pHigh[0], pHigh[1], pHigh[3]);
printf("/n");
printf(" Lowest Grade: %s %s %d", pLow[0], pLow[2], pLow[3]);
printf("/n");
printf(" Average Grade: %d",pAverage);
}
The main chunk of problems come from the searchData function. In the if statements, every occurrence of *sPointArray and &sPointArray is underlined in red and the error reads
"Error: expression must have class type"
The same thing also happens in the calculateAvg function with *avgPointArray in the for loop. I know that the error is a fairly common problem for noobie C programmers (i.e myself) and that it generally has to do with writing the code as a function instead of a statement or something like that, but I can't for the life of me find where I have went wrong. Any help would be highly appreciated. I've been working at this for so long my vision is blurring.
Also, for anyone who solves this in like two seconds and wants proof that I'm a true idiot, there is an error in the enterStudents function where it says StudPtr = malloc(sizeof...). The error shows under the assignment symbol and says
"Error: a value of type "void*" cannot be assigned to an entity of type "int*".
I understand this concept in theory, but some advice for how to fix it would be highly appreciated.
Thank you in advance for any help.
You declare the sPointArray as an array of integers, but use it as an array of structures.

Resources