C - variables in header file not recognized - arrays

I'm new to C and I'm trying to create an online grocery store where I can add items to the store and print the details of each product such as the name, number in stock, price, etc.
I'm having trouble adding a product to a product collection array and getting it to print. My biggest issue is that main.c seems to not recognize practically every variable declared in defs.h even though I used the include tag at the top of the file. I'm also not sure if my addProd() function makes sense and was hoping someone could verify?
main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "defs.h"
int main(){
InventoryType store;
store.storeName = "Walmart";
ProductCollectionType p;
p.numProd = 0;
addProd(&p, 1001, "Grape juice", 12.5);
addProd(&p, 1002, "Pepsi", 4.3);
addProd(&p, 1003, "Apples", 34.0);
int choice;
printf("(1) Print inventory");
printf("(0) Exit");
printf(" ");
printf("Please enter your choice: ");
scanf("%d", choice);
if(choice == 1){
store->printInventory(p)
}
return 0;
}
void printInventory(ProductCollectionType* productArray){
int i;
for(int i = 0; i < numProd; ++i) {
printf("The BLANK store");
printf("-- Product #%d, %s, %d units, $ %.2f", productArray[i].id, productArray[i]->name, productArray[i].numUnits, productArray[i].price);
}
}
int addProd(ProductCollectionType* productArray, int givenId, char givenName, int givenUnits, float givenPrice){
for(i = 0; i < numProd; ++i){
productArray[i].id = givenId;
productArray[i].name = givenName;
productArray[i].numUnits = givenUnits;
productArray[i].price = givenPrice;
}
}
defs.h
#define MAX_NAME 40
#define MAX_PROD 20
#define MAX_UNITS 15
typedef struct{
int id;
char *name;
int numUnits;
float price;
}ProductType;
typedef struct {
ProductType* products[MAX_UNITS];
int numProd;
int nextId;
}ProductCollectionType;
typedef struct{
char *storeName;
ProductCollectionType* productArray[MAX_PROD];
}InventoryType;

Regarding the code:
void printInventory(ProductCollectionType* productArray){
int i;
for(int i = 0; i < numProd; ++i){
blah blah blah
There is no such thing as the "naked" numProd, numProd is a field of the ProductCollectionType type. Hence you would need something like:
for (int i = 0; i < productArray->numProd; ++i) {

Related

Using structures in C with user defined functions

I had came across a problem that I have tried so many times with different ways but still not able to obtain the required solution please do help me.
PROBLEM: Define a structure to store students’ details. Pass them to a function where the student with HIGHEST CGPA is calculated from a set of 5 students. And display the result.(Here we have to store name, age and CGPA obtained of each student)
Here is my try at the problem:
#include <stdio.h>
void highCGPA(float b,struct detst D[4]);
struct detst
{
int age;
float CGPA;
char name[30];
};
int main()
{
struct detst D[4];
int i;
float h;
for(i=0;i<=4;i++)
{
printf("Enter the name of student %d:\n",i+1);
scanf("%s",&D[i].name);
printf("Enter the age of student %d:\n",i+1);
scanf("%d",&D[i].age);
printf("Enter the CGPA obtined by student %d:\n",i+1);
scanf("%f",&D[i].CGPA);
}
highCGPA(h,D);
}
void highCGPA(float b,struct detst D[4])
{
int i,max;
max = D[0].CGPA;
for(i=0;i<=4;i++)
{
if(D[i].CGPA > max)
{
max = D[i].CGPA;
}
}
printf("Highest CGPA obtained is:\n%f",max);
}
There is more than one problem. You're trying to store the data of 5 students in an array of struct with size 4. So:
struct detst D[5]; // fixed size
int i;
float h;
for(i=0;i<5;i++) { // EDIT (comments suggestion): for loop fix following standard convetions
/* take input */
}
Lastly, if you declare max as an int, you can't try to print it with a format specifier for float. So:
printf("Highest CGPA obtained is: %d\n",max); // format specifier for int is %d (not %f)
There are couple of other problems.
your declaration of funtion highCGPA is above your struct detst definition
you should have got error
error: array type has incomplete element type ‘struct detst’
declare your function after the structure definition.
your max variable is int in the function highCGPA , but you are trying to store a float value in it.
With a sligth change to program functionallity can be improved:
#include <float.h> // FLT_MAX
#include <stdio.h>
struct detst
{
int age;
float CGPA;
char name[30];
};
// Return offset of student with highest CGPA
int highCGPA(struct detst const (*D)[5]); // Using pointer to array
// to avoid degeneration
int main()
{
struct detst D[5];
int i;
for(i = 0; i < 5; i++)
{
printf("Enter the name of student %d:\n", i + 1);
scanf("%29s", D[i].name); // Make sure we don't overwrite the buffer
printf("Enter the age of student %d:\n", i + 1);
scanf("%d", &D[i].age);
printf("Enter the CGPA obtained by student %d:\n", i + 1);
scanf("%f", &D[i].CGPA);
}
int bestStudentOffset = highCGPA(&D); // By asking for best student
// we can obtain a lot more
printf(
"Best student is %d year old %s with\n",
D[bestStudentOffset].age,
D[bestStudentOffset].name);
printf("Highest CGPA obtained is:\n%f\n", D[bestStudentOffset].CGPA);
}
// Return offset of student with highest CGPA
int highCGPA(struct detst const (*D)[5])
{
int i, maxOffset = -1;
float max = -FLT_MAX;
for(i = 0; i < 5; i++)
{
if((*D)[i].CGPA > max)
{
max = (*D)[i].CGPA;
maxOffset = i;
}
}
return maxOffset;
}

data types different in C

how to do we declare parallel arrays in C. And also , how to add more than one data type in a single array. for example, i want to declare int and char data type in the same array
#include <stdio.h>
int main()
double linetotal= qty*price;
printf("line total =%lf\n",linetotal);
double subtotal = line total - discount ;
}
}
Check the solution now.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define NUM_CODE 10
const char *CODE[NUM_CODE] = {"B100","B122","B134","B138","B145","B160","B165","B178","B186","B194"};
double PRICE[NUM_CODE]={12.8,18.7,20.5,11.5,25.5,20.55,25.65,14.85,22.2,24.25};
int main()
{
char name[20];
printf("Enter buyer name: ");
scanf("%s",name);
int entry;
printf("Enter number of entries for the invoice: ");
scanf("%d",&entry);
char code[10];
int quantity;
double price,linetotal=0;
int i;
for(i=1;i<=entry;i++)
{
printf("Enter Code: ");
scanf("%s",code);
printf("Enter Quantity: ");
scanf("%d",&quantity);
printf("Enter Unit Price: ");
scanf("%lf",&price);
int j;
int flag=0;
for(j=1;j<=NUM_CODE;j++){
// how do i print values like B100 without getting errors//
printf("%s ",CODE[j-1]);
// how to match the user input with parallel arrays?//
if(strcmp(CODE[j-1],code)==0 && PRICE[j-1]==price){
//If correct code and price found do
printf("\nValid Code and price found\n");
//set the flag and break from the loop
flag=1;
break;
}
}
if(flag==0){
//Exit the program with invalid entry
printf("\nInvalid Code and price found\n");
printf("The program will close now...\n");
exit(1);
}
// how do calculate line total,and subtotal after discount//
// discount is 10% if line total is greater than Rs5000//
linetotal = price * quantity + linetotal;
printf("\n");
}
double subtotal;
if(linetotal>5000){
subtotal = 0.9*linetotal;
}
else if(linetotal>=1000 && linetotal<=5000){
subtotal = 0.95*linetotal;
}
else{
subtotal = linetotal;
}
printf("Discount: %0.2lf%%\nTotal Price: %lf\n",((linetotal-subtotal)/linetotal)*100,subtotal);
return 0;
}

Building a struct with a function

Hello i'm trying to build a function to search a car for a client by client demand.
The structure contains: model,year,price.
the client is asked to enter his demands and then the code calls a function that check if there is a car in the structure that is suitable for him.
I get error for "access violation reading error"
thanks!
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#define SIZE 10
typedef struct
{
char model[10];
float price;
int year;
}car;
void findCar(car *arr[], int minYear, float maxPrice, char modelWanted, int carAmount);
int main()
{
int carAmount;
car* arr;
puts("How many cars?");
scanf("%d", &carAmount);
arr = (car*)malloc(carAmount * sizeof(car));
if (arr == NULL)
return -1;
for (int i = 0; i < carAmount; i++)
{
puts("Enter car details, Model, Price,Year");
scanf("%s%f%d",arr[i].model,&arr[i].price,&arr[i].year);
}
char modelWanted[SIZE];
float maxPrice;
int minYear;
puts("Enter wanted model,maximum price and minimum year!");
scanf("%s%f%d", modelWanted, &maxPrice, &minYear);
for (int i = 0; i < carAmount; i++)
printf("Model is: %s, Price is: %.2f, Year is: %d\n", arr[i].model, arr[i].price, arr[i].year);
findCar(&arr, minYear, maxPrice, modelWanted, carAmount);
free(arr);
return 1;
}
void findCar(car *arr[], int minYear, float maxPrice, char modelWanted,int carAmount)
{
int i, counter = 0;
for (i = 0; i < carAmount; i++)
if (((strcmp(arr[i]->model, modelWanted)) == 0) && (arr[i]->year >= minYear) && (arr[i]->price <= maxPrice))
{
printf("Model is: %s, Price is: %.2f, Year is: %d\n", arr[i]->model, arr[i]->price, arr[i]->year);
++counter;
}
printf("We found %d cars for you!", counter);
}
You are passing pointer to array of struct
car *arr[]
so instead of accessing elements by arr[i]->model like you do, you should access them using (*arr)[i].model. The method you uses is for accessing the array of pointers to struct element, but you have pointer to array of struct.
Of course already commented char instead of char* will also cause run time error, but you should have received compiler warning for this.

Implementing a Linear Search

The question:
Read up to 6 pairs of names and ages into TWO separate arrays, and use a linear search to locate a target name and to print that person’s age. The two arrays are called names and ages:
I am getting lots of errors .. I am not sure about passing the arrays into functions..
#include <stdio.h>
#define ASIZE 20
#define RECSIZE 6
struct record {
char name[ASIZE];
int age[ASIZE];
};
struct record na[RECSIZE];
int linearSearch(struct record *a, char *find)
{
int x;
for(x=0; x<RECSIZE; x++)
{
// if(na[x].name==find[x])
if(a->name[x]==find[x])
{
return x;
}
}
return -1;
}
int main()
{
int i;
for (i=0; i<RECSIZE; i++)
{
printf("Enter name: ");
scanf("%s",na[i].name);
printf("Enter age: ");
scanf("%i",&na[i].age);
}
printf("Enter the Search name: ");
char temp[ASIZE];
scanf("%s",temp[ASIZE]);
int result;
result=linearSearch(&na, &temp[]);
printf("%i", result);
return 0;
}
Please help.
The error is in:
result=linearSearch(&na, &temp[]);
#include <stdio.h>
#include <string.h>
#define ASIZE 20
#define RECSIZE 6
struct record {
char name[ASIZE];
int age;
};
struct record na[RECSIZE];
int linearSearch(struct record *a, char *find){
int x;
for(x=0; x<RECSIZE; x++){
if(strcmp(a[x].name, find)==0)
return x;
}
return -1;
}
int main(){
int i;
for (i=0; i<RECSIZE; i++){
printf("Enter name: ");
scanf("%s", na[i].name);//No protection when entered past the buffer
printf("Enter age: ");
scanf("%i", &na[i].age);
}
printf("Enter the Search name: ");
char temp[ASIZE];
scanf("%s", temp);
int result;
result=linearSearch(na, temp);
printf("%i", result);
return 0;
}
On my system, the compiler gave me these errors for your exact code. Just look at the line numbers (should be exactly like yours) and address each error by looking at the error description. Once you address these, you will be further down the path of understanding your execution flow:

Segmentation Error in C program When Run

I've tried malloc, and no malloc and it will build but not run or compile. When I run the code on codepad.org it gives me a segmentation error. I have an array of structures I'm inputting and I'm searching through them for a specific item. That's as far as I got and no compile. The code is as follows (I used netbeans, codeblocks, and visual basic 2012 programs):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 20
#define BLOODTYPESIZE 4
#define MAX 120000
typedef struct {
int month;
int day;
int year;
} dateT;
typedef struct {
int hour;
int minute;
} timeT;
typedef struct {
char name[SIZE];
char organname[SIZE];
char bloodtype[BLOODTYPESIZE];
dateT dateAdded;
timeT timeAdded;
int received;
} organT;
int main(void) {
int i, n, k, j;
int c;
int *ptr;
char organ[SIZE];
char bloodkind[BLOODTYPESIZE];
organT patient[MAX];
scanf("%d",&n);
ptr = (int *)malloc(n * sizeof(*ptr));
printf("Enter patient information\n");
for(i=1; i<=n; i++){
scanf("%s", patient[i].name[SIZE]);
scanf("%s", patient[i].organname[SIZE]);
scanf("%s", patient[i].bloodtype[BLOODTYPESIZE]);
scanf("%d %d %d", patient[i].dateAdded);
scanf("%d %d", patient[i].timeAdded);
patient[i].received = 0;
}
scanf("%d", &k);
for(j=0; j<k; j++) {
gets(organ);
printf("Organ received: %s", organ);
gets(bloodkind);
printf("Organ has blood type: %s", bloodkind);
}
for (c=0; c<n; c++){
if(patient[i].organname == organ){
if(patient[i].bloodtype == bloodkind){
if(patient[i].received == 0) {
printf("Patient(s) Found!\n");
printf("%s", patient[i].name[SIZE]);
printf("Organ received: %s", organ);
patient[i].received = 1;
}
if(patient[i].received == 1)
printf("Patient already received organ\n");
}
else("Not correct blood type\n");
}
else("No match found\n");
}
return (EXIT_SUCCESS);
}
Looks like you are not using the address correctly. For example, when you say
scanf("%s", &patient[i].name[SIZE]);
you are actually reading past the allocated space for patient[i].name. You should change the statement to
scanf("%s",patient[i].name);
and fix other statements similarly.
First check n compare to MAX
here you access to bloodtype[BLOODTYPESIZE] but the last item in this tab is bloodtype[BLOODTYPESIZE-1]
scanf("%s", &patient[i].bloodtype[BLOODTYPESIZE]);
The same problem is tru for other acces in the pararagraph.

Resources