Pointers within structures - c

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.

Related

use printf and scanf on char *

I'm having problems inputting values into this structure template, please help.
I've got to use char* for those attributes. so it doesn't give an error while inputting data but crashes when its time to display.
#include<stdio.h>
#include<malloc.h>
#include<conio.h>
struct Date
{
int day;
char *month;
int year;
}date;
struct sports_team
{
char *name;
char *city;
int no_of_players;
struct Date creation_date;
};
void main()
{
struct sports_team *my_team;
my_team = (struct sports_team*)malloc(sizeof(struct sports_team)*2);
printf("fill information for teams:\n");
for(int i=0;i<2;i++)
{
printf("\nenter team name:");
scanf("%s",&my_team[i].name);
printf("\nenter team city:");
scanf("%s",&my_team[i].city);
printf("\nenter no. of players:");
scanf("%d",&my_team[i].no_of_players);
printf("\nenter creation day:");
scanf("%d",&(my_team[i].creation_date.day));
printf("\nenter creation month:");
scanf("%s",&(my_team[i].creation_date.month));
printf("\nenter creation year:");
scanf("%d",&(my_team[i].creation_date.year));
printf("\n\n");
}
printf("\n information for teams:\n");
for(int i=0;i<2;i++)
{
printf("%s ",my_team[i].name);
printf("%s ",my_team[i].city);
printf("%d ",my_team[i].no_of_players);
printf("%d ",my_team[i].creation_date.day);
printf("%s ",my_team[i].creation_date.month);
printf("%d ",my_team[i].creation_date.year);
printf("\n\n");
}
free(my_team);
}
you're allocating the structures all right but you're forgetting to allocate memory for char * members: you're writing into uninitialized memory when doing scanf (not to mention that you're passing the address of the pointer, not the pointer itself: don't use & when scanning strings).
For simplicity's sake, you could just put fixed buffer lengths in your structures:
struct Date
{
int day;
char month[20];
int year;
}date;
struct sports_team
{
char name[100];
char city[100];
int no_of_players;
struct Date creation_date;
};
and limit size when scanning (don't use & when scanning strings BTW)
scanf("%99s",my_team[i].name);
scanf("%99s",my_team[i].city);
scanf("%19s",my_team[i].creation_date.month);
Use getchar() instead of scanf().

I cannot store integer in structure

I created a struct Book with the properties.I let the user to create the structure objects with for-loop.Like Books[i] Books1, Books2 etc...
The problem is that i cant store integer values in the structure.
The code is given below.
#include <stdlib.h>
#include <stdio.h>
struct Book {
int ID[];
char book_name[80];
char author_name[50];
int pblsh_date[];
};
struct Book *Books;
void Create();
int main() {
int count;
printf("How many books do you want to enter? ");
scanf("%d", &count);
Create(count);
//Show
printf("ID\t\tName\tAuthor\tPublish Year\n");
for (int i= 0; i < count; i++)
printf("%d\t%s\t%s\t%d\n", Books[i].ID, Books[i].book_name, Books[i].author_name, Books[i].pblsh_date);
if (Books) {
free(Books);
}
getchar();
return 0;
}
void Create(int count) {
Books = (struct Book*) malloc(count * sizeof(struct Book));
int i;
for (i = 0; i < count; i++) {
printf("%d. Book's ID: ", i+1);
scanf("%d", Books[i].ID);
printf("Book's name: ");
scanf("%s", Books[i].book_name);
printf("Author: ");
scanf("%s", Books[i].author_name);
printf("Publish Year: ");
scanf("%d", Books[i].pblsh_date);
}
}
The definition of the structure that you posted contains two empty arrays: int ID[]; and int pblsh_date[];. Since you did not specify a size and the compiler is not throwing an error, it is not allocating any storage for the array data: the arrays are zero-length and you are overwriting the data that follows them when you scanf into them.
Since you only want a single integer, the correct way to define the structure is
struct Book {
int ID;
char book_name[80];
char author_name[50];
int pblsh_date;
};
The only other change you need to make to your program is the arguments to scanf: scanf("%d", &(Books[i].ID)); and scanf("%d", &(Books[i].pblsh_date));. The reason is that scanf requires the address of the place you want to put the result. While scanf("%s", Books[i].book_name); works as is, you need to add the & operator to int variables. book_name is an array, which in C is treated as a pointer containing the address of the buffer you want to write to. ID is an int, so you need to get its address to know where to write to. Notice how you already did this in main with scanf("%d", &count);.

Assigning user input values to allocated memory

The idea behind the program is to declare a data structure for student information, then have the user input information into each field of the data structure for an inputted amount of students. My issue is the program stops working when I input the first name. What is wrong? Thank you for your time.
//Inclusion of necessary header files
#include <stdio.h>
#include <stdlib.h>
//Data structure declaration
struct student{
char firstName[20];
char lastName[20];
char id[10];
char gender;
int age;
double gpa;
};
//Function prototypes
void readStudentsInformation(struct student *, int size);
void outputStudents(struct student *, int size);
double averageGPA(struct student *, int size);
void sortByLastName(struct student *, int size);
void sortByGPA(struct student *, int size);
//Entry point
int main()
{
//Variable delcaration
int size;
struct student *ptr;
//Input prompt and function
printf("How many students?\n");
scanf_s("%d", &size);
//Allocation memory for struct student times the number of students and assigning it to a struct student pointer for external function modification
ptr = (struct student*)malloc(sizeof(struct student)*size);
//readStudentsInformation Function call
readStudentsInformation(ptr, size);
//Exit sequence
return 0;
}
//This functions reads the information for all the students from the keyboard, taking the class size through the pointer method and struct student from main
void readStudentsInformation(struct student *ptr, int size)
{
//For loop controller declaration
int i;
//Function message
printf("Student Information Form\n");
//This for loop increments the "index" of each students info location where user input is stored
for(i=0;i<size;i++)
{
//Each field has it's appropriate input limit
printf("Please enter Student %d's First Name(20 characters).\n", i+1);
scanf_s("%20s", ptr[i].firstName);
printf("Please enter Student %d's Last Name(20 characters).\n", i+1);
scanf_s("%20s", ptr[i].lastName);
printf("Please enter Student %d's ID(10 characters).\n",i+1);
scanf_s("%10s", ptr[i].id);
printf("Please enter Student %d's gender(M/F).\n",i+1);
scanf_s("%c", ptr[i].gender);
printf("Please enter Student %d's age.\n",i+1);
scanf_s("%3d", ptr[i].age); //Only 3 digits can be put in at a time
printf("Please enter Student %d's GPA.\n", i+1);
scanf_s("%.1lf", ptr[i].gpa); //From the lab it can be seen that no more than one decimal place is featured, so the same is done here
}
//Exit to main
return;
}
You should do
scanf_s("%20s", ptr[i].firstName);
to read first name. ptr+i will give you student structure. You want to store data in the structure member.
Change your other scanfs as well for this.
You can use
scanf("%s",ptr[i].firstName);
and so on for the rest of the structure members in your scanf()'s.
change scanf_s to scanf and change this block as follow:
scanf("%c", &ptr[i].gender);
printf("Please enter Student %d's age.\n",i+1);
scanf("%3d", &ptr[i].age); //Only 3 digits can be put in at a time
printf("Please enter Student %d's GPA.\n", i+1);
scanf("%1lf", &ptr[i].gpa);

Pointer to an array of structures

I'm currently trying to write a program for a student database assignment. After manually setting 3 elements of the structure array, the next 3 students' details are inputted by the user.
I am trying to write a function that finds the oldest age of the 6 students and returns it as a student_t entry at index max. I'm struggling with how to actually give the function the pointer that is pointing to the first element of the array stdt[6] and then using the pointer within the function. I also have no idea how I would go about returning to main the entry that has the highest age. If I'm trying to say that the value of an element of array of structures is equal to some other integer (max), doesn't that mean that max is now some other block of memory with an integer value and not linked to the array? So I'm not sure how I would return the entry that has the highest age after the function determines the max age.
This is all I've written so far:
#include <stdlib.h>
#include <stdio.h>
typedef struct {
char *name;
char *surname;
char *UUN;
char *department;
char gender;
int age;
}student_t;
student_t findOldest(student_t *studentarr, int len){
int i;
int x;
int max;
max=0;
for(i=0;i<len;i++){
(p+i).age=x;
if(x>max){
x=max;
}
}
}
int main() {
int i;
student_t stdt[6]={{"John","Bishop","s1234","Inf",'m',18},{"Lady","Cook","s2345","Eng",'f',21},{"James","Jackson","s33456","Eng",'m',17}};
student_t *p=&stdt[0];
for(i=3;i<6;i++) {
printf("First name: \n");
scanf("%s",stdt[i].name);
printf("Last name: \n");
scanf("%s",stdt[i].surname);
printf("UUN: \n");
scanf("%s",stdt[i].UUN);
printf("Department: \n");
scanf("%s",stdt[i].department);
printf("Gender (m/f): \n");
scanf("%c",stdt[i].gender);
printf("Age: \n");
scanf("%d",stdt[i].age);
}
findOldest(p,6);
return 0;
}
This should work.
student_t findOldest(student_t *p, int len){
int i;
student_t max = *(p+0);
for(i=1;i<len;i++)
{if((*(p+i)).age > max.age)
max = *(p+i);
}
return max;
}
You want to return the student so keep the student in your max variable not the age. And to refer to pointers either use
(p+i)->age > max.age
or use
(*(p+i)).age > max.age
But there are other problems with the code.

return value type does not match function type c programming linked list

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define maxchar 50
int numcars;
int c;//counter
char fu[5];//debug
int main()
{
typedef struct car //info of car
{
int year;
char vin[maxchar];
char make[maxchar];
char model[maxchar];
car *next;
};
car *first;
car *newcar;
printf("Enter the Number of Cars you have: ");
scanf("%i", &numcars);
struct car *addtolist(struct car *first);
{
newcar = (car*)malloc(sizeof(car));
printf("\nEnter The Model Year: ");
scanf("%i", &newcar->year);
printf(" ");//for some reason the program always skips the first 'gets' so this one is here to take that hit.
gets(fu);
printf("\nEnter The Make: ");
gets(newcar->make);
printf("\nEnter The Model: ");
gets(newcar->model);
printf("\nEnter The Vehicle Identifaction Number: ");
gets(newcar->vin);
newcar->next = first;
first = newcar;
return newcar;
}
}
I am a student learning linked lists and this is a homework project.
The function 'struct car *addtolist(struct car *first)' was originally not a function but was simply enclosed in a for loop, looping 'numcar' times, while I was getting it to work properly, which I did.
For the next step I simply wanted to add the function bits, the declaration and return, and then enclose the call for the function in a for loop.
My problem is that the compiler keeps telling me that the return type does not match the function type.
What did I do wrong?
struct car *addtolist(struct car *first);
{
As long as you write these 2 lines inside main(), you declared the function prototype of addtolist(), and started a scope. You are not defining the function addtolist(). Thus, the later return newcar; returns a variable with incorrect type since main() returns int.

Resources