error while input in structure pointer - c

Error after providing the input value of ID. But working when values directly assigned. Compiled Successfully.
#include<stdio.h>
#include <string.h>
typedef struct student
{
char name[20];
int id;
int mob;
} stu;
void printstudent(stu *stud);
void main()
{
stu s1;
strcpy(s1.name,"name");
printf("Enter Student id");
scanf("%d",s1.id);
//s1.id=1;
printf("Enter Student Mob no");
scanf("%d",s1.mob);
//s1.mob=9911;
printstudent(&s1);
}
void printstudent(stu *stud)
{
printf("\n%d",stud->id);
printf("\n%s",stud->name);
printf("\n%d",stud->mob);
}
Error after providing the input value of ID. But working when values directly assigned.

s1.id and s1.mob are not pointers to the int, you should use &s1.id and &s1.mob

Related

Allocating memory for a struct variable using a function

As part of a larger project, I am trying to write a function that will allocate enough memory for a struct variable and assign values to its member variables after scanning them from the keyboard. In other words, I am trying to create a sort of a constructor function. The reason for this is because I think that's the best way to create a database-like program in c, where all the student_t variables will be stored in a student_t* array called classroom.
#include <stdio.h>
#include <stdlib.h>
#define N 10
#define STRLIM 50
typedef struct student{
char* name;
int age;
}student_t;
student_t* init_student(student_t* s);
int i=0;//its the array counter
student_t* classroom[N];
int main(int argc, char const *argv[]){
while(i<N){
// classroom[i]=(student*)malloc(sizeof(student));
init_student(classroom[i]);
classroom[i]->age=i;
printf("The age of student #%d is : %d \n",i,classroom[i]->age);
printf("the name of student #%d is : %s",i,classroom[i]->name);
i++;
}
printf("the size of the classroom is : %ld",sizeof(classroom));
return 0;
}//end of main()
student_t* init_student(student_t* s){
s=(student_t*)malloc(sizeof(student_t));
s->name=(char*)malloc(sizeof(char)*STRLIM);
fflush(stdin);
fgets(s->name,STRLIM,stdin);
return s;
}
Gdb ouput shown in the attached image here.
Please check out my repo.
I am guessing something about my build and datatypes is off .Thanks in advance.

C program - skipping user input

I created a program that uses arrays and array pointers to store a user's animal name, category of animal, and age. But when I run it, there is a segmentation fault after I type the name age and category. I was wondering if someone could guide me in how to fix it, I am very new to C programming.
This is the task I am supposed to complete:
Write a program that defines an animal data type, with an animal name, age, and category (cat, dog, etc.), as well as an animal array type that stores an array of animal pointers.  Your program will prompt the user to enter the data for as many animals as they wish.  It will initialize a dynamically allocated animal structure for each animal, and it will store each animal in an instance of the animal array structure.  Your program will then print all the animal information to the screen.  You will upload your C program as one file.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
char *name;
char *category;
int age;
} AnimalType;
typedef struct {
AnimalType basicInfo;
AnimalType *arr[];
} AnimalArrayType;
void initAnimal(char *n, char *c, int a, AnimalArrayType *ar);
void printAnimal(const AnimalArrayType *stuPtr);
int main() {
AnimalArrayType *array;
int numAn;
char name[20];
char category[20];
int age;
printf("Please enter the number of animals you want to input: ");
scanf("%d", &numAn);
array = calloc(numAn, sizeof(AnimalArrayType));
for (int i=0; i<numAn; ++i) {
printf("Enter animal name: ");
scanf("%s", name);
printf("Enter their category: ");
scanf("%s", category);
printf("Enter age: ");
scanf("%d", &age);
initAnimal(name, category, age, array + I);
}
printf("\n LIST:\n");
for (int i=0; i<numAn; ++i) {
printAnimal(array + I);
}
return 0;
}
void initAnimal(char *n, char *c, int a, AnimalArrayType *ar)
{
strcpy(ar->basicInfo.name, n);
strcpy(ar->basicInfo.category, c);
ar->basicInfo.age = a;
}
void printAnimal(const AnimalArrayType *stuPtr)
{
printf("Animal: %s, Category: %s age %d\n",
stuPtr->basicInfo.name, stuPtr->basicInfo.category,
stuPtr->basicInfo.age);
}
The char *name and char *category fields in the AnimalType struct are being initialized to NULL (from the call to calloc()), but you don't allocate any char[] memory for them to point at afterwards, so you end up crashing in initAnimal() when it tries to copy data into those fields using strcpy().
You need to either:
change those fields into char[] arrays instead of char* pointers:
typedef struct {
char name[20];
char category[20];
int age;
} AnimalType;
allocate memory for them to point at, such as from strdup():
typedef struct {
char *name;
char *category;
int age;
} AnimalType;
...
void initAnimal(char *n, char *c, int a, AnimalArrayType *ar)
{
ar->basicInfo.name = strdup(n);
ar->basicInfo.category = strdup(c);
ar->basicInfo.age = a;
}
Don't forget to free() anything you dynamically allocate when you are done using it.

Error expected expression before struct

The errors that prevent my code from compiling are:
[Error] expected identifier or '(' before '.' token
[Error] expected expression before 'books'
[Error] too few arguments to function 'fread'
I'm new to C programming and programming altogether. Although I'm used to Pascal. The errors occur in all functions except in the main and void menu. This is only a part of my code.
Please can someone help me in solving these errors this program.
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>
char catergories[][15]={"Computer","Philosophy","Arts","Literature","Science","History"};
void menu(void);
void addbooks(void);
void deletebooks(void);
void updatebooks(void);
void findbooks(void);
void sellbooks(void);
void viewbooks(void);
int enterinfo();
int checkid(int);
void Password();
//list of global files that can be accessed from anywhere in program
FILE *fp,*ft,*fs;
//list of global variable
int s;
char findbook;
char password[10]={"dominique"};
typedef struct
{
int mm,dd,yy;
}OrderDate;
typedef struct
{
int id;
char name[35];
char author[35];
int quantity;
float price;
int count;
int shelf;
char *cat;
struct OrderDate *sold;
}books;
void addbooks(void) //funtion that add books
{
system("cls");
int i;
struct books;
printf("\n ******************************************************\n");
printf("\n \t\t ADD A BOOK");
printf("\n ******************************************************\n\n");
printf("\n SELECT THE CATERGORY OF THE BOOK:");
printf("\n 1. Computer Science, Information & General Works");
printf("\n 2. Philosophy, Psychology and Religion");
printf("\n 3. Arts and Recreation");
printf("\n 4. Literature");
printf("\n 5. Science");
printf("\n 6. History and Geography");
printf("\n 7. Back to main menu\n");
printf("\n Enter your choice:");
scanf("%d",&s);
if(s==7)
{
menu() ;
}
system("cls");
fp=fopen("BookRecords.txt","ab+");
if(enterinfo()==1)
{
books.cat=catergories[s-1]; //the error that exists here states expected identifier or '(' before '.' token
fseek(fp,0,SEEK_END);
fwrite(&books,sizeof(books),1,fp); //the error that exists here states expected expression before 'books'
fclose(fp);
printf("\n The book's information has been saved sucessfully");
printf("\n Would you like to save more information? (Y/N):");
if(getch()=='n')
{
menu();
}
else
system("cls");
addbooks();
}
}
struct books;
books is your type name. Like int or char. Thats why books.id==d won't work. You have to declare variable that is type of books. For example:
books BooksInMyShop;
Now you can use your variable in code ex.:
if(BooksInMyShop.id == currentId)
PS1: When You define:
typedef struct
{
(...)
}books;
You dont need to declare variable by struct books BooksInMyShop; simple books BooksInMyShop; will work now.
PS2: I can see in your code lots of missconceptions. For example "variable" books in every function in not shared beetween them. I guess You have to pass one instance of Your bookstore to every function or have one static global instance.

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);

Calling a typedef'd struct to a function?

I'm trying to call a structure to a function but I'm getting the error: 'course' undeclared
The error is in the hw3func program. I typedef'd my structure and malloc'd space for it inside of main, but I don't know what I need to make my function prototype or my function call to recognize the struct? Thank you for the help in advance!!
hw3.c:
#include <stdio.h>
#include <stdlib.h>
#include "hw3func.c"
int main(void)
{
coursestruct *course = malloc(1*sizeof(coursestruct));
studentstruct *student = malloc(1*sizeof(studentstruct));
display();
menu();
return 0;
}
hw3.h:
#include <stdio.h>
#include <stdlib.h>
/*Start of prototypes*/
void display(void);
void menu(void);
void newcourse(int coursetotal, coursestruct *course);
void newstudent(int studenttotal);
/*End of prototypes*/
/*Start of initial struct declares*/
// coursestruct *course = malloc(1 * sizeof(coursestruct));
// studentstruct *student = malloc(1 * sizeof(studentstruct));
/*End of initial struct declares*/
/*Start of variables*/
int coursetotal=0;
int studenttotal=0;
/*End of variables*/
hw3struct.h:
typedef struct{
char name[50];
int id[4];
}coursestruct;
typedef struct{
char name[20];
int id[8];
}studentstruct;
hw3func.c
#include <stdio.h>
#include <stdlib.h>
#include "hw3struct.h"
#include "hw3.h"
void display(void)
{}
void menu(void)
{
int loop=0; /*Loop for the menu*/
while(loop==0)
{
int option;
printf("\n\n\nWelcome to the grade book! Select your option below.\n");
printf("1= Add a new course.\n");
printf("2= Add a new student.\n");
printf("3= Add a student to a course.\n");
printf("4= Add grades for a student in a course.\n");
printf("5= Print a list of all grades for a student in a course.\n");
printf("6= Print a list of all students in a course.\n");
printf("7= Compute the average for a student in a course.\n");
printf("8= Print a list of all courses.\n");
printf("9= Print a list of all students.\n");
printf("10= Compute the average for a course.\n");
printf("11= Store grade book to a disk file.\n");
printf("12= Load grade book from a disk file.\n");
printf("13= Exit grade book.\n");
scanf("%d",&option);
printf("\n\n\n");
if(((option>0) && (option<14)))
{
switch(option)
{
case 1:
newcourse(coursetotal,course);
break;
case 13:
loop=1;
break;
default:
break;
}
}
else
{
printf("Please input a number between 1-13.\n");
}
}
}
void newcourse(int coursetotal, coursestruct *course)
{
}
You declare coursestruct *course inside main, so it is not directly accessible from other functions (like your menu() function).
You should do some reading on variable scope in C.
In this case, the proper fix is most likely to change your function declarations to something like
void menu (coursestruct *course);
Then call it from main as menu(course);. This allows the menu function access to the variable declared inside main.

Resources