struct and variable looping C language - c

#include <stdio.h>
struct Car {
char brand[50];
char model[50];
int year;
};
int main() {
struct Car car1 = {"BMW", "X5", 1999};
struct Car car2 = {"Ford", "Mustang", 1969};
struct Car car3 = {"Toyota", "Corolla", 2011};
printf("%s %s %d\n", car1.brand, car1.model, car1.year);
printf("%s %s %d\n", car2.brand, car2.model, car2.year);
printf("%s %s %d\n", car3.brand, car3.model, car3.year);
return 0;
}
/*
BMW X5 1999
Ford Mustang 1969
Toyota Corolla 2011
*/
Here the struct only has 3 variables (car1, car2, car3). But if it had numerous cars, how could I make this same code (print all values) using a loop?

You need an array of Cars, something like this
#include <stdio.h>
struct Car {
char brand[50];
char model[50];
int year;
};
int main() {
struct Car cars[] = {
{"BMW", "X5", 1999},
{"Ford", "Mustang", 1969},
{"Toyota", "Corolla", 2011},
{"Mercedes", "C197", 2010 }
};
for(size_t i = 0; i < sizeof(cars)/sizeof(cars[0]); ++i) {
printf("%s %s %d\n", cars[i].brand, cars[i].model, cars[i].year);
}
return 0;
}

You need an array of struct Car.
It works pretty much the same as any other array in with the difference that each element now has extra fields, the ones on your struct.
Here is an example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 100
struct Car {
char brand[50];
char model[50];
int year;
};
int main(void) {
struct Car cars[SIZE];
for (int i = 0; i < SIZE; i++) {
// Initialize
strcpy(cars[i].brand, "BMW"); // or any other brand
strcpy(cars[i].model, "X5");
cars[i].year = 1999;
}
for (int i = 0; i < SIZE; i++) {
// Print
printf("Car %d:\n", i + 1);
printf("%s %s %d\n", cars[i].brand, cars[i].model, cars[i].year);
}
return 0;
}

Related

Unable to read a structure from a text file in C

#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int id;
char* name;
float weight;
} Person;
int main()
{
Person *person=malloc(10*sizeof(Person));
int i=0;
char row[20];
FILE *input=fopen("input.txt","r+");
while(fscanf( input, "%s", &row)>0) i++;
i/=5;
printf("%d\n", i);
fseek(input,0,SEEK_SET);
int j;
char string[20];
for (j=0;j<i;j++){
fscanf(input,"%s",string);
fscanf(input,"ID:%d",&person[j].id);
fscanf(input,"Name:%s",person[j].name);
fscanf(input,"Weight:%f",&person[j].weight);
fscanf(input,"%s",string);
}
fclose(input);
//Person:{
//ID:1214124141
//Name:Trump
//Weight:101.50
//}
//Person:{
//ID:5235252525
//Name:Obama
//Weight:78.30
//}
return 0;
}
Hello!
I want to read a structure from a file, but my array person contains only 0 even after I read from the file. My input file has the structure shown in the comment lines.
What am I not doing well?
Thanks a lot for the help!
fix like this
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
long long int id;//32bit int can't hold like 5235252525
char name[20];//Allocate space
float weight;
} Person;
#define FORMAT "%*s ID:%lld Name:%19[^\n] Weight:%f %*s"
int main(void){
FILE *input=fopen("input.txt", "r+");
if(!input){
perror("fopen");
return -1;
}
int n = 0;
Person p;
while(3==fscanf(input, FORMAT, &p.id, p.name, &p.weight))
++n;
printf("number of record: %d\n", n);
Person *person = malloc(n * sizeof(Person));
if(!person){
perror("malloc");
fclose(input);
return -2;
}
rewind(input);
for (int i = 0; i < n; ++i){
fscanf(input, FORMAT, &person[i].id, person[i].name, &person[i].weight);
}
fclose(input);
//check print
for (int i = 0; i < n; ++i){
printf("ID:%lld, Name:%s, Weight:%.2f\n", person[i].id, person[i].name, person[i].weight);
}
free(person);
return 0;
}

Struct fl has no member named sub

#include <stdio.h>
#include <stdlib.h>
struct fl{
char sub[3] = {"Math","Science","ICT"};
};
int main()
{
int i;
struct fl floatp;
for (i = 0; i < 3; ++i){
printf (" %s",floatp.sub[i]);
}
return 0;
}
I am getting this error "struct fl has no member named sub" on the 11th line. But i do have a member named 'sub'. What am i doing wrong?
You want this:
#include <stdio.h>
#include <stdlib.h>
struct fl {
char *sub[3];
};
int main()
{
int i;
struct fl floatp = {{ "Math","Science","ICT" }};
// or if your compiler supports it:
// struct fl floatp = {.sub = { "Math","Science","ICT" }};
for (i = 0; i < 3; ++i) {
printf(" %s", floatp.sub[i]);
}
return 0;
}

Check Structure, add items if not already in structure. C

I'm trying to do some practice programming and I've come to a, for me, a difficult problem.
The problem is I'm supposed to write a program the will take the make and model of a car that was "entered" and place it in the structure, if the make an model are not there, otherwise it does nothing.
This is what I have so far, and I keep getting errors:
#include <stdio.h>
#include <string.h>
void addCar(struct car u, int* count, char *make[], char *model[]);
struct car { char make[30]; char model[30]; };
int main(void)
{
struct car unique[10] = {{"Ford", "Explorer"}, {"Honda", "Civic"},
{"Honda", "Accord"}, {"Chevy", "Malibu"}};
int i, count = 4;
addCar(unique, &count, "Ford", "Mustang");
}
void addCar(struct car u, int* count, char *make[], char *model[])
{
}
The line that says addCar(unique, &count,... it's saying "Argument type 'struct car' is incomplete" and the last line says "conflicting types for addCar"
Could you all give me a few pointers, please?
EDIT:
Okay, here is what my code is now, but I still can't get it to work. Any other suggestions would be appreciated!
#include <stdio.h>
#include <string.h>
struct car { char make[30]; char model[30]; };
void addCar(struct car *u, int *count, char *make, char *model);
int main(void)
{
struct car unique[10] = {{"Ford", "Explorer"}, {"Honda", "Civic"},
{"Honda", "Accord"}, {"Chevy", "Malibu"}};
int i, count = 4;
printf("%s", unique[0].make);
addCar(unique, &count, "Ford", "Mustang");
}
void addCar(struct car *u, int *count, char *make, char *model)
{
int i = 0;
for (i; i < *count; i++)
{
if ((u[i].make != make) && (u[i].model != model))
{
strcpy(u->make, make);
strcpy(u->model, model);
count++;
}
}
for (i = 0; i < *count; i++)
printf("%s, %s", u[i].make, u[i].model);
}
struct car unique[10] = {{"Ford", "Explorer"}, {"Honda", "Civic"},
{"Honda", "Accord"}, {"Chevy", "Malibu"}};
This is an array of struct car, therefore, you need to declare your addCar function as follow
void addCar(struct car *u, int *count, char *make, char *model)
*make and *model represent 2 strings. You have a mistake when you have char *make[], which declares an array of string.
Your function prototype for addCar is defined and uses 'struct car' before you define 'struct car'. Try moving the structure definition above the prototype for addCar.
Here are a few things that I figured out when looking at your code.
In this case, I think it's best if you use while loop rather than for loop.
Secondly, if you want to make sure that the car you want to add does not exist in the list, I suggest you use this
while (i < *size) {
if ((u[i].make == make) && (u[i].model == model)) { break; } // check if the car is already in the list
i++;
}
It checks the whole list for the existence of an element with the same make and model.
Here is the code I modified from yours. I hope it helps you.
#include <stdio.h>
#include <string.h>
struct car { char make[30]; char model[30]; };
void addCar(struct car *u, int *count, char *make, char *model);
int main(void)
{
struct car unique[10] = {{"Ford", "Explorer"}, {"Honda", "Civic"},
{"Honda", "Accord"}, {"Chevy", "Malibu"}};
int i, count = 4;
addCar(unique, &count, "Ford", "Mustang");
for (i = 0; i < count; i++) {
printf("%s, %s\n", unique[i].make, unique[i].model);
}
}
void addCar(struct car *u, int *size, char *make, char *model)
{
int i = 0;
while (i < *size) {
if ((u[i].make == make) && (u[i].model == model)) { break; } // check if the car is already in the list
i++;
}
if (i == *size) { // car found
struct car c;
strcpy(c.make, make);
strcpy(c.model, model);
u[i] = c;
(*size)++;
}
}

How to create a struct on the stack in C?

I understand how to create a struct on the heap using malloc. Was looking for some documentation regarding creating a struct in C on the stack but all docs. seem to talk about struct creation on heap only.
The same way you declare any variable on the stack:
struct my_struct {...};
int main(int argc, char **argv)
{
struct my_struct my_variable; // Declare struct on stack
.
.
.
}
To declare a struct on the stack simply declare it as a normal / non-pointer value
typedef struct {
int field1;
int field2;
} C;
void foo() {
C local;
local.field1 = 42;
}
an answer to 17.4 Extra Credit (in Zed's book "Learn C the Hard Way") using functions
#include <stdio.h>
struct Person {
char *name;
int age;
int height;
int weight;
};
struct Person Person_create(char *name, int age, int height, int weight)
{
struct Person who;
who.name = name;
who.age = age;
who.height = height;
who.weight = weight;
return who;
}
void Person_print(struct Person who)
{
printf("Name: %s\n", who.name);
printf("\tAge: %d\n", who.age);
printf("\tHeight: %d\n", who.height);
printf("\tWeight: %d\n", who.weight);
}
int main(int argc, char *argv[])
{
// make two people structures
struct Person joe = Person_create("Joe Alex", 32, 64, 140);
struct Person frank = Person_create("Frank Blank", 20, 72, 180);
//print them out and where they are in memory
printf("Joe is at memory location %p:\n", &joe);
Person_print(joe);
printf("Frank is at memory location %p:\n", &frank);
Person_print(frank);
// make everyone age 20 and print them again
joe.age += 20;
joe.height -= 2;
joe.weight += 40;
Person_print(joe);
frank.age += 20;
frank.weight += 20;
Person_print(frank);
return 0;
}
I got it to work this way:
#include <stdio.h>
struct Person {
char *name;
int age;
int height;
int weight;
};
int main(int argc, char **argv)
{
struct Person frank;
frank.name = "Frank";
frank.age = 41;
frank.height = 51;
frank.weight = 125;
printf("Hi my name is %s.\n", frank.name);
printf("I am %d yeads old.\n", frank.age);
printf("I am %d inches tall.\n", frank.height);
printf("And I weigh %d lbs.\n", frank.weight);
printf("\n-----\n");
struct Person joe;
joe.name = "Joe";
joe.age = 50;
joe.height = 93;
joe.weight = 200;
printf("Hi my name is %s.\n", joe.name);
printf("I am %d years old.\n", joe.age);
printf("I am %d inches tall.\n", joe.height);
printf("And I weigh %d lbs.\n", joe.weight);
return 0;
}

"struct" objects with "for-loop" in C Programming

This code is about 'struct' in C..
I created a struct spieler with the properties name and age..
By using the for-loop I let the user to create the struct objects.
they are named as sp[i] --> sp1, sp2 etc.
the problem is the objects are created. But I can use them only inside the for-loop.
If I want to get the value of "sp1.name" in main function, it doesn't work.
How can I solve it?
struct spieler{
char name[20];
int age;
};
void erzeuge();
int main() {
int anzahl = 2;
printf("Anzahl Spielern: ");
scanf("%d",&anzahl);
erzeuge(anzahl);
printf("Es sind %d Spielern",anzahl);
/*for(i;i<anzahl;i++){
printf("%d.%s",i, sp[i].name);
}*/
getchar();
}
void erzeuge(int anzahl){
int i=0;
for(i;i<anzahl;i++){
struct spieler sp[i];
printf("Struct fuer Spieler_%d wurde erzeugt\n", i);
getchar();
printf("Name: ");
scanf("%s",sp[i].name);
printf("%s\n",sp[i].name);
}
You should declare sp as a pointer at the global scope, and allocate memory for it inside the function erzeuge using malloc.
#include <stdlib.h>
#include <stdio.h>
struct spieler {
char name[20];
int age;
};
struct spieler *sp; // Add this
void erzeuge();
int main() {
int anzahl;
printf("Anzahl Spielern: ");
scanf("%d", &anzahl);
erzeuge(anzahl);
printf("Es sind %d Spielern\n", anzahl);
int i;
for(i = 0; i < anzahl; i++){
printf("%d.%s\n", i, sp[i].name);
}
if (sp) {
free(sp);
}
getchar();
return 0;
}
void erzeuge(int anzahl) {
// Add the following line to allocate memory
sp = (struct spieler*) malloc(anzahl * sizeof(struct spieler));
int i;
for (i = 0; i < anzahl; i++) {
// Remove the following line because it create an array of "i" elements
// struct spieler sp[i];
printf("Struct fuer Spieler_%d wurde erzeugt\n", i);
getchar();
printf("Name: ");
scanf("%s",sp[i].name);
printf("%s\n",sp[i].name);
}
}
You'd have to return an array of players from erzeuge, something like
struct spieler *erzeuge(int anzahl){
struct spieler *mannschaft = malloc(anzahl*sizeof(struct spieler));
int i;
for(i = 0; i < anzahl; ++i){
// prompt
scanf("%18s",&mannschaft[i].name);
...
}
return mannschaft;
}
Alternative solution without malloc:
void erzeuge(struct spieler* sp, int anzahl)
{
...
}
int main()
{
int anzahl = 2;
...
struct spieler sp[anzahl];
erzeuge(sp,anzahl);
...
}

Resources