is it possible to use two different structures in the same code? - c

I need to add another structure to my code and I wish to know if this is possible?
Below is a snippet of what I want to do.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include "math.h"
#define MAX_CARS 10
struct car {
double vel, position, desired_vel;
int index, on_network;
};
typedef struct car Car;
struct car_2 {
double vel_2, position_2, desired_Vel_2;
int index, on_network;
};
typedef struct car_2 Car_2;

You can have unlimited struct types in your code. In this instance though, as they both are identical, you can re-use your Car struct and make separate instances with it.
Car car1;
Car car2;
car1.vel = 5.0;
car2.vel = 10.0;

Yes you can use as many as you want. Example code as below:
#include <stdio.h>
struct car_dim
{
int feet;
float inch;
} card;
struct showroom_loc
{
int lid;
int pin;
} carl;
int main()
{
printf("enter the information for card struct\n");
printf("Enter feet: \n");
scanf("%d", &card.feet);
printf("Enter inch: \n");
scanf("%f", &card.inch);
printf("enter the information for car location struct\n");
printf("enter lid e\n");
scanf("%d", &carl.lid);
printf("Enter pin: \n");
scanf("%f", &carl.pin);
printf("struct card= %d\'-%.1f\"", card.feet, card.inch);
printf("\nstruct carl= %d\'-%.1f\"", carl.lid, carl.pin);
return 0;
}

You can use as many structures in your code as you like as long as their name is different.
However in your example, the members of your structures are identical, maybe you want to do something like this?
#define MAX_CARS 10
struct car {
double vel, position, desired_vel;
int index, on_network;
};
typedef struct car Car;
int main() {
// You can define as many instances of type "Car" as you want
Car car1;
Car car2;
Car car3;
// Or you can use arrays
Car cars[MAX_CARS];
cars[0].desired_vel = 100.0;
cars[1].desired_vel = 120.0;
// and so on
return 0;
}

Related

Compilation error in function declaration in C

I am getting errors during the compilation of this C program and is related to the declaration of the function. What is the problem here? When I declare void display(student); it shows a warning but if I change to void display(struct student st) it shows some errors.
#include<stdio.h>
void display(student);
void read_student(student);
struct student{
int roll;
char name[20],depart[20],sex,result;
float percent,marks[5],total;
};
void main(){
int n;
printf("enter the no of data you want to enter ??");
scanf("%d",&n);
struct student s[n];
for(int i=0;i<n;i++)
read_student(&s[i]);
printf("\n---------------------------------------------------Result Sheet --------------------------------------------------------------------");
printf("\nRoll No.\tName\t\tSex\tDepartment\t\tMarks\t\t\t\tTotal\tPercentage\tResult ");
printf("\n----------------------------------------------------------------------------------------------------------------------------------------");
printf("\n \t\t\t\tA\tB\tC\tD\tE\n");
printf("----------------------------------------------------------------------------------------------------------------------------------------");
for(int i=0;i<n;i++)
display(s[i]);
}
void display(struct student st){
printf("\n%2d\t%10s\t\t%c\t%10s\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%4.2f\t %2.2f\t\t%c\n",st.roll,st.name,st.sex,st.depart,st.marks[0],st.marks[1],st.marks[2],st.marks[3],st.marks[4],st.total,st.percent,st.result);
}
void read_student(struct student *std){
int c=0,i;
printf("Enter the roll no:");
scanf("%d",&std->roll);
printf("enter the name:\n");
scanf("%s",std->name);
printf("enter Sex:\n");
scanf(" %c",&std->sex);
printf("Enter the department:\n");
scanf("%s",std->depart);
printf("enter the marks in 5 subjects:\n");
for(i=0;i<5;i++){
scanf("%f",&std->marks[i]);
std->total=std->total+std->marks[i];
if(std->marks[i]>=40)
c++;
}
if(c==5)
std->result='p';
else
std->result='f';
std->percent=(std->total/500)*100;
}
The compiler needs to know what struct student is, when using it elsewhere in the code, for example declaring a function with it as type of an argument/parameter. The compiler reads the source file from top to bottom. You need to declare the structure before you use it as a type in the declaration of a function:
struct student; // forward declaration of structure `student`.
void display(struct student); // ok, because `struct student` is declared before.
void read_student(struct student*); // ok, because `struct student` is declared before.
struct student{ // definition of structure `student`.
int roll;
char name[20],depart[20],sex,result;
float percent,marks[5],total;
};
Alternatively, you can define the structure before the declarations of the functions:
struct student{ // define the structure `student` before the function declarations.
int roll;
char name[20],depart[20],sex,result;
float percent,marks[5],total;
};
void display(struct student);
void read_student(struct student*);
Another way would be to put the definitions of the functions read_student and display before main(), but after the the definition of the structure student. In this way you can omit the separate declarations of the functions read_student and display and of course the forward declaration of the structure student as well:
#include<stdio.h>
struct student{
int roll;
char name[20],depart[20],sex,result;
float percent,marks[5],total;
};
void read_student(struct student *std){
int c=0,i;
printf("Enter the roll no:");
scanf("%d",&std->roll);
printf("enter the name:\n");
scanf("%s",std->name);
printf("enter Sex:\n");
scanf(" %c",&std->sex);
printf("Enter the department:\n");
scanf("%s",std->depart);
printf("enter the marks in 5 subjects:\n");
for(i=0;i<5;i++){
scanf("%f",&std->marks[i]);
std->total=std->total+std->marks[i];
if(std->marks[i]>=40)
c++;
}
if(c==5)
std->result='p';
else
std->result='f';
std->percent=(std->total/500)*100;
}
void display(struct student st){
printf("\n%2d\t%10s\t\t%c\t%10s\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%4.2f\t %2.2f\t\t%c\n",st.roll,st.name,st.sex,st.depart,st.marks[0],st.marks[1],st.marks[2],st.marks[3],st.marks[4],st.total,st.percent,st.result);
}
int main(){
int n;
printf("enter the no of data you want to enter ??");
scanf("%d",&n);
struct student s[n];
for(int i=0;i<n;i++)
read_student(&s[i]);
printf("\n---------------------------------------------------Result Sheet --------------------------------------------------------------------");
printf("\nRoll No.\tName\t\tSex\tDepartment\t\tMarks\t\t\t\tTotal\tPercentage\tResult ");
printf("\n----------------------------------------------------------------------------------------------------------------------------------------");
printf("\n \t\t\t\tA\tB\tC\tD\tE\n");
printf("----------------------------------------------------------------------------------------------------------------------------------------");
for(int i=0;i<n;i++)
display(s[i]);
}
At the declaration of functions you can omit identifiers of parameters, but not the type of parameters.
It is also not permissible to use the structure student without preceding the struct keyword as you tried it with:
void display(student);
since you use the structure student by its definition:
struct student{
...
};
If you would use a typedef like for example:
typedef struct student{
...
} student;
You could omit the struct keyword, but if you use a typedef or just use the structure as it is, is a kind of controversy topic amongst the community with regards to readibility. All references to that, you can see on the answers to these questions:
typedef struct vs struct definitions
Why should we typedef a struct so often in C?
I personally recommend to keep on using the struct variant, even if it requires a little bit more typing with the keys, but makes your code a little bit clearer.

C forward-referencing structures - 1) must be with a pointer? 2) must be initialized?

I'm trying to forward reference a (nested) structure, in C.
That means I have a structure and in it I'm referencing to another structure that is declared later.
If I declare the nested structure as a pointer, and initialize it with values, it works.
The following code works:
#include <stdio.h>
struct computer{
double cost;
int year;
char cpu_type[16];
struct cpu_speed *sp; //this is the question (1)
};
struct cpu_speed{
int num;
char type[16];
};
typedef struct computer SC;
typedef struct cpu_speed SS;
void DataR(SC *s);
void DataP(SC *s);
int main(){
// this is question (2)
SS speed = {4,"giga"};
SC model[2] = {
{ 0,1990, "intel", &speed},
{ 0,1990, "intel", &speed}
};
int i;
for(i=0;i<2;i++) {
printf("computer no. %d \n", i+1);
DataR(&model[i]);
}
printf("here's what you entered: \n");
for(i=0;i<2;i++) {
printf("computer no. %d \n", i+1);
DataP(&model[i]);
}
return 0;
}
void DataR(SC *s){
printf("the cost of your computer: ");
scanf("%lf", &s->cost);
printf("the year of your computer: ");
scanf("%d", &s->year);
printf("the type of cpu inside your computer: ");
scanf("%s", s->cpu_type);
printf("the speed of the cpu: ");
scanf("%d %s", &(s->sp->num), s->sp->type);
}
void DataP(SC *s){
printf("the cost: %.2lf\n",s->cost);
printf("the year: %d\n",s->year);
printf("the cpu type: %s\n",s->cpu_type);
printf("the cpu speed: %d %s\n",s->sp->num, s->sp->type);
}
If I declare the nested struct (i.e. struct cpu_speed{...};) before the parent(?) struct, I do not need to use a pointer, and I also don't need to initialize.
Meaning:
(1) I can use struct cpu_speed speed; instead of struct cpu_speed *sp;.
(2) I do not need to give initialized values to the structures variables.
My questions again - in forward referencing structure - (1) do you have to declare it with a pointer? and (2) do you have to initialize the values?
Structures are only used by the compiler to align your memory. Thus, it needs to know the size of struct members.
struct foo {
struct bar *pointer;
};
In this case, the sizeof(pointer) is unrelated to the bar struct and thus the compiler does not need to know anything more.
However, if you want to add the bar struct to the foo struct, it does need to know about its individual members.
struct bar {
const char *string;
uint64_t integer;
};
struct foo {
struct bar sub;
};
You need to declare the bar struct before foo because the compiler needs to know what you're referring to. Otherwise, how would it know what to do with this (illegal) code:
struct bar {
struct foo sub;
};
struct foo {
struct bar sub;
};

Pointers within structures

I am new to c language and I tried to create a structure. so here is the my structure.
typedef struct car{
int *transmission;
int *year;
char color[15];
}CAR;
Then I tried to insert the values to the structure variables using below code,
printf("Enter M Year of car : ");
scanf("%d",car1.year);
printf("Enter color of car : ");
scanf("%s",&car1.color);
printf("Enter transmission type of car (1 for manual & 2 for auto): ");
scanf("%d",car1.transmission);
But, it returns an error. pls help me to resolve the issue.
In this structure you shouldn't declare pointers, but variables
#include <stdio.h>
#include <stdlib.h>
struct car
{
int transmission;
int year;
char color[15];
};
int main()
{
struct car car1;
printf("Enter M Year of car: ");
scanf("%d", &car1.year);
printf("\nThe year of the car is: %d", car1.year);
return 0;
}
The problem is that you have not intialized the pointers in your struct with the address of any actual int variables, so they contain garbage.
On the other hand, the color variable is a pointer that DOES point to the first of the 15 chars, therefore you donĀ“t have to pass its address to scanf(), but just its value so that the function can store there the chars read.
Try someting like this:
int aYear, aTransmission;
CAR car1;
car1.year = &aYear;
car1.transmission = &aTransmission;
printf("Enter M Year of car : ");
scanf("%d",car1.year);
printf("Enter color of car : ");
scanf("%s",car1.color); /* color IS a pointer */
printf("Enter transmission type of car (1 for manual & 2 for auto): ");
scanf("%d",car1.transmission);
This code will store the values into the extern variables aYear and aTransmission, which are pointed by the pointers into the struct.

C - passing structure + members by value

my questions here always seem to be about using functions. It still confuses me! In this textbook exercise i am asked to pass a structure by value, then adjust it and pass by reference. Initially I designed the code to have everything done in main. Now I am passing by value. So I added the new function, and I figured I passed the structure correctly but I am getting an error at line
void function1(struct Inventory inv){ that tells me parameter 1 (inv) has incomplete type. please help!
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void function1(struct Inventory inv);
struct Inventory{
char name[20];
int number;
float price;
float total;
}
void main(){
items;
void function1(items);
float total = items.number*items.price;
printf("Item\tNumber\tPrice\tTotal\tAddress of number\n");
printf("%s\t%d\t%.2f\t%.2f\t%X\n\n",items.name,items.number,items.price,total,&items.number);
getch();
}
void function1(struct Inventory inv) {
printf("Enter the name of the item: ");
scanf("%s", inv.name);
printf("Enter the number of items: ");
scanf("%d", &inv.number);
printf("Enter the price of each item: ");
scanf("%f", &inv.price);
}
You have to define your struct BEFORE you use it in your function prototype.
struct Inventory{
char name[20];
int number;
float price;
float total;
}items;
void function1(struct Inventory inv);

Getting multiple struct entries from stdin

I am trying to get multiple entries for my struct via the keyboard. I think I am wrong inside of scanf but I am not sure where I am wrong. Thanks!
Here is what I have:
#include <stdio.h>
#include <math.h>
int main()
{
//define the structure
struct course
{
char title[20];
int num;
} ;
// end structure define
//define the variable
struct course classes;
printf("Enter a course title and course number");
scanf("%s %d", classes[3].title, &classes.num);
return 0;
}
Fix the code as Carl said and it works fine:
#include <stdio.h>
int main()
{
struct course
{
char title[20];
int num;
} ;
struct course class;
printf("Enter a course title and course number");
scanf("%s %d", class.title, &class.num);
printf("%s %d", class.title, class.num);
return 0;
}
There are a couple issues.
You have this struct called "classes", but it has only 1 entry - you're accessing the 3rd entry so you're running off the end.
Also, Title is 20 bytes long, but if you enter something larger in scanf(), it will just overflow. The basic scanf() structure looks ok though.
I would set it up more like this:
#include <stdio.h>
#include <math.h>
#define MAX_CLASSES 50 // how big our array of class structures is
int main()
{
//define the structure
struct course
{
char title[20];
int num;
} ;
// end structure define
//define the variable
struct course classes[MAX_CLASSES];
int nCurClass = 0; // index of the class we're entering
bool bEnterMore = true;
while (bEnterMore == true)
{
printf("Enter a course title and course number");
scanf("%s %d", classes[nCurClass].title, &classes[nCurClass].num);
// if user enters -1 or we fill up the table, quit
if (classes[nCurClass].num == -1 || nCurClass > MAX_CLASSES-1)
bEnterMore = false;
}
}
That's the basic idea. Another improvement that could be made would be checking the length of the course title before assigning it to classes[].title. But you need something to do ;-)

Resources