I'm having trouble getting a struct pointer to take user input through fgets inside a function in a c program; I'm not sure what I'm doing wrong. The getInput() function is where the crash is occurring. I'm first trying to assign memory to the where the name is going to be stored with
*stu->name = (char*)malloc(N_LENGTH);
then getting input from the user with
fgets(*stu->name, N_LENGTH, stdin);
The program crashes during the first line and also the second line.
Sorry if I'm breaking any rules as this is my first time on the site.
Code:
#include <stdio.h>
#include <stdlib.h>
#define UNIT 100
#define HOUSE 1000
#define THRESH 12
#define DISCOUNT 10
#define NUM_PERSONS 5
#define N_LENGTH 30
struct student
{
char *name;
char campus;
int userUnit;
};
void getInput(struct student *stu);
int amountCalc(struct student *stu);
void printOutput(struct student stu, int total);
int main()
{
int total[NUM_PERSONS];
int averageTotal=0;
struct student tempStudent;
struct student students[NUM_PERSONS];
struct student *sPtr = &tempStudent;
int i;
for (i=0; i < NUM_PERSONS; i++)
{
getInput(sPtr);
students[i]=tempStudent;
total[i]=amountCalc(sPtr);
averageTotal+=total[i];
};
for (i=0; i < NUM_PERSONS; i++)
{
printOutput(students[i], total[i]);
};
printf("\nThe average tuition cost for these %d students is $%.2f.\n",
NUM_PERSONS, averageTotal/(NUM_PERSONS*1.0));
return 0;
}
void getInput(struct student *stu)
{
fflush(stdin);
printf("Enter student name: ");
*stu->name = (char*)malloc(N_LENGTH);
fgets(*stu->name, N_LENGTH, stdin);
printf("Enter y if student lives on campus, n otherwise: ");
scanf(" %s", &stu->campus);
printf("Enter current unit count: ");
scanf(" %d", &stu->userUnit);
printf("\n");
}
int amountCalc(struct student *stu)
{
int total;
total=(stu->userUnit)*UNIT;
if (stu->userUnit>THRESH) {
total-=((stu->userUnit)-12)*DISCOUNT;
};
if (stu->campus=='y') {
total+=HOUSE;
};
return total;
}
void printOutput(struct student stu, int total)
{
printf("\nStudent name: %s\n", stu.name);
printf("Amount due: $%d\n\n", total);
}
Your allocation is wrong. True allocation is like this ;
void getInput(struct student *stu)
{
fflush(stdin);
printf("Enter student name: ");
stu->name = (char*)malloc(N_LENGTH);
fgets(stu->name, N_LENGTH, stdin);
printf("Enter y if student lives on campus, n otherwise: ");
scanf(" %s", &stu->campus);
printf("Enter current unit count: ");
scanf(" %d", &stu->userUnit);
printf("\n");
}
When you compile it, you can see as a warning. You should take care of all warnings. And casting malloc to (char *) is also unnecessary.
Don't use fflush(stdin). See this question. I don't know if that causes the error but it is not defined in the C-standard so maybe your platform doesn't handle it!
The wrong allocation of memory is also a problem, look at #Hakkı Işık 's answer.
Related
Fields of Student: name, lastName, studentId, mid1Grade, mid2Grade, finalGrade, average
Fields of Course: courseName, courseCode, myStudentArray (array of Student structures),currentStudentCount
Functions:
void createNewStudent(struct Course *myCourse);
void setGradeOfStudent(struct Course *myCourse);
void findAndDisplayAverage(struct Course *myCourse);
struct Student * findStudentByID(int id, struct Course *myCourse);
void displayAverageOfAllStudents(struct Course *myCourse);
void displayAverageOfStudentsInInterval(struct Course *myCourse
ok so I have written the first function but there is an error which I dont understand. First of all the first function and what it does:
createNewStudent: Prompt the user to enter name, last name and id of the new student.Values entered by the user are assigned to the fields of the student residing in themyStudentArray of course variable pointed by myCourse. currentStudentCount will be updated so that it designates the slot allocated for the student inserted next.
and my implementation:
#include <string.h>
#include <stdio.h>
struct Student {
char name[50];
char lastname[50];
int id;
int mid1;
int mid2;
int final;
double average;
};
struct Course {
char courseName[50];
char courseCode[50];
struct Student myStudentArray[5];
int currentstudentcount;
};
void createNewStudent(struct Course * myCourse);
void setGradeOfStudent(struct Course * myCourse);
void findAndDisplayAverage(struct Course * myCourse);
struct Student * findStudentByID(int id, struct Course * myCourse);
void displayAverageOfAllStudents(struct Course * myCourse);
void displayAverageOfStudentsInInterval(struct Course * myCourse);
int main() {
struct Student * stud;
int input = 0;
scanf("%d", & input);
if (input == 1) {
createNewStudent(struct Course * myCourse);
}
}
return 0;
}
void createNewStudent(struct Course * myCourse) {
struct Student s1;
printf("Enter name: ");
scanf("%[^\n]%*c", s1.name);
printf("Enter Surname: ");
scanf("%[^\n]%*c", s1.lastname);
printf("Enter id: ");
scanf("%d", & s1.id);
}
When you call the function with the if(input == 1) it gives
error: expected expression before ‘struct’
but I dont understand this beacuse *myCourse is just a pointer to the Course struct isn't it ????
If I can understand this ı will be able to the the next functions I think
Is the function correct ?? I dont know why this doesnt work
Ok I tried to use the struct Student myStudentArray[5]; to get name, lastname,id like so (structs are the same)
void createNewStudent(struct Course *myCourse);
void setGradeOfStudent(struct Course *myCourse);
int main(){
struct Course *myCourse;
int input=0;
scanf("%d",&input);
if(input == 1){
createNewStudent(myCourse);
}
return 0;
}
void createNewStudent(struct Course *myCourse){
myCourse->currentstudentcount=0;
printf("Enter name: ");
scanf("%[^\n]%*c"
,myCourse->myStudentArray[myCourse->currentstudentcount].name);
printf("Enter Surname: ");
scanf ("%[^\n]%*c",
myCourse->myStudentArray[myCourse->currentstudentcount].name);
myCourse->currentstudentcount++;
}
I Keep getting
may be used uninitialized in this may be used uninitialized in this function [-Wmaybe-uninitialized]
and
Segmentation errors
void createNewStudent(struct Course * myCourse)
If you want to create new student, you should use the student struct as the parameter of this function instead of using struct Course.
void createNewStudent(struct Student *s1)
Then, this function becomes as:
void createNewStudent(struct Student *s1) {
printf("Enter name: ");
scanf("%49s", s1->name);
printf("Enter Surname: ");
scanf("%49s", s1->lastname);
printf("Enter id: ");
scanf("%d", & s1->id);
}
If you want to test, in main function, you can declare the value stud or the pointer to struct Student.
For example:
int main() {
struct Student stud;
int input = 0;
scanf("%d", & input);
if (input == 1) {
createNewStudent(&stud);
printf("name: %s\n Surname: %s\n id = %d\n", stud.name, stud.lastname, stud.id);
}
return 0;
}
The complete program for test:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
struct Student {
char name[50];
char lastname[50];
int id;
int mid1;
int mid2;
int final;
double average;
};
struct Course {
char courseName[50];
char courseCode[50];
struct Student myStudentArray[5];
int currentstudentcount;
};
void createNewStudent(struct Student *s1);
int main() {
struct Student stud;
int input = 0;
scanf("%d", & input);
if (input == 1) {
createNewStudent(&stud);
printf("name: %s\nSurname: %s\nid = %d\n", stud.name, stud.lastname, stud.id);
}
return 0;
}
void createNewStudent(struct Student *s1) {
printf("Enter name: ");
scanf("%49s", s1->name);
printf("Enter Surname: ");
scanf("%49s", s1->lastname);
printf("Enter id: ");
scanf("%d", & s1->id);
}
The output:
#./test
1
Enter name: abc
Enter Surname: def
Enter id: 100
name: abc
Surname: def
id = 100
Update for your question in the comment:
If you want to store student info in an array, you can change the code to:
struct Student myStudentArray[5];
int input = 0;
scanf("%d", & input);
if (input == 1) {
for (int i = 0; i < 5; i++) {
createNewStudent(&myStudentArray[i]);
}
for (int i = 0; i < 5; i++) {
printf("name: %s\nSurname: %s\nid = %d\n", myStudentArray[i].name, myStudentArray[i].lastname, myStudentArray[i].id);
}
}
For Course structure you can create one function as the function createNewStudent but for struct Course to create the new course. After creating new 5 students (for example the code above), you can copy the myStudentArray to new_course.myStudentArray. Then now you have the info of 5 students in new_course. When you copy value from an array to another, you can use memcpy or using one loop to copy each element from one array to another one. Do not use something like myStudentArray = new_course.myStudentArray for the array.
You are making a declaration as a parameter of the createNewStudent() function. In C, functions require expressions as parameters, which is why you got the error message "expected expression...".
So, just create the struct pointer before you call the function:
if (input == 1) {
struct Course *myCourse = malloc(sizeof(struct Course));
createNewStudent(myCourse);
}
Notice the use of malloc(), which returns a pointer to a place in memory of sufficient size to hold that particular Course struct. When dealing with pointers to structs, you need to allocate memory for the structs that will ultimately be pointed to, in order to avoid dereferencing unallocated regions of memory.
In your function CerateNewStudent, the proper way to address the variables into which to place the data read by scanf should be:
myCourse->myStudentArray[myCourse->currentstudentcount].name
as the variable to read name into. Use this syntax for all data items to read. After that, increment the counter:
myCourse->currentstudentcount++;
Note: what is missing in all your functions (and in the assignment?) is a way to create a course. The students created are all added to courses. First a course should be created and then students can be added to it.
I'm trying to call two functions, the first function will receive data and the second will show the data. But my second function is equal to the first, so it doesn't do what I intend to do. Any suggestions guys?
struct Operador
{
char nome[32];
char telefone[15];
char idade[3];
};
struct Operador* fun( ) {
struct Operador* pItems = malloc( 3 * sizeof(struct Operador));
int n;
for(n=0;n<1;n++){
printf(" name: "); gets(pItems[n].nome);
printf(" telefone: "); gets(pItems[n].telefone);
printf(" age: "); gets(pItems[n].idade);
}
return pItems;
}
//*-*-**-*-*-*-*-*-*-*-*-*-*-*-*-*-*--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-**-*fim_operador
void lo()
{
struct Operador* pItems =fun();
int j;
printf("\n\n");
for(j=0;j<1;j++){
printf(pItems[j].nome);
printf(pItems[j].telefone);
printf(pItems[j].idade);
printf("\n\n");
}
free(pItems);
}
main()
{
fun();
lo();/ i want this function to simply display data
Some alterations in your code:
in function fun() instead of gets maybe it would be better to use scanf.
in function fun() and lo() you access your pointer to a struct with the '.' operator.
you should use the '->' operator instead.
i do not understand why you use a for loop to get and print the values while you have only one value but i suppose you have your reasons (maybe to add more structs at a future implementation.
below i suggest a code you could use:
#include <stdio.h>
#include <stdlib.h>
struct Operador
{
char nome[32];
char telefone[15];
char idade[3];
};
struct Operador* fun() {
struct Operador* pItems = malloc(3 * sizeof(struct Operador));
//int n;
//for (n = 0; n<1; n++){
printf(" give nome: ");
scanf("%s", pItems->nome);
printf(" give telefone: ");
scanf("%s", pItems->telefone);
printf(" give age: ");
scanf("%s", pItems->idade);
//}
return pItems;
}
//*-*-**-*-*-*-*-*-*-*-*-*-*-*-*-*-*--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-**-
void lo(void)
{
struct Operador* pItems = fun();
// int j;
printf("\n\n");
// for (j = 0; j<1; j++){ //no need for "for"?
printf("Name is: %s \n", pItems->nome);
printf("telefone is: %s \n", pItems->telefone);
printf("age is: %s \n", pItems->idade);
printf("\n\n");
// }
free(pItems);
return;
}
main()
{
//fun(); //no need to call, is called in lo()
lo();
}
the output is:
give nome: jim
give telefone: 2673673
give age: 32
Name is: jim
telefone is: 2673673
age is: 32
Press any key to continue . . .
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
So I am having a problem when compiling this program, I just can't get it to work, I mean if I put the inputstudent() code inside the main(), it is much easier but I have to place the code in a function, inputstudent() and call in from the main(). I know it sounds very easy but I can't get it.
#include <stdio.h>
#include <stdlib.h>
struct student
{
char surname[50];
int age;
char oname[50];
char address[50];
};
void displaystudent();
void inputstudent();
int main(){
struct student s;
inputstudent(s);
displaystudent(s);
return 0;
}
void inputstudent(struct student s){
printf("Enter the surname: ");
scanf("%s",s.surname);
printf("Enter the other name: ");
scanf("%s",s.oname);
printf("Enter the age: ");
scanf("%d",&s.age);
printf("Enter the address: ");
scanf("%s",s.address);
}
void displaystudent(struct student s)
{
printf("Surname: %s \n",s.surname);
printf("Oname: %s \n",s.oname);
printf("Age: %d \n",s.age);
printf("Address: %s",s.address);
}
In C parameters are passed by value, so any modifications made to a parameter inside the function will be local modifications.
Lets have a look at following code snippet which is basically a very simple version of what you're trying to do:
void GetNumber(int number)
{
printf("Type a number:\n");
scanf("%d", &number); // modifies the local variable `number`?
}
...
int n = 0;
GetNumber(n);
Now what is the value of n right after the call to GetNumber?
Well it's not the number the user has typed, but it's still 0, that is the value n contained prior to the call to GetNumber.
What you need is this:
void GetNumber(int *pnumber)
{
printf("Type a number:\n");
scanf("%d", pnumber); // modifies the value pointed by the pointer pnumber
}
...
int n = 0;
GetNumber(&n); // &n is the memory address of the variable n
You need to read the chapter dealing with pointers in your C textbook.
Other less important problem
Your prototypes
void displaystudent();
void inputstudent();
don't match the corresponding functions.
You are passing your struct by value, that's why the function is not modifying it. You should change your function that is intended to modify the struct to take a struct pointer as argument:
#include <stdio.h>
#include <stdlib.h>
struct student {
char surname[50];
int age;
char oname[50];
char address[50];
};
void displaystudent(struct student s);
void inputstudent(struct student *s);
int main() {
struct student s;
inputstudent(&s);
displaystudent(s);
return 0;
}
void inputstudent(struct student *s) {
printf("Enter the surname: ");
scanf("%s", s->surname);
printf("Enter the other name: ");
scanf("%s", s->oname);
printf("Enter the age: ");
scanf("%d", &s->age);
printf("Enter the address: ");
scanf("%s", s->address);
}
void displaystudent(struct student s) {
printf("Surname: %s \n", s.surname);
printf("Oname: %s \n", s.oname);
printf("Age: %d \n", s.age);
printf("Address: %s", s.address);
}
As mentioned by Michael Walz, use pointers in order to modify structure in function calls. Moreover your function signature and definition does not match that's why compiler is complaining:
#include <stdio.h>
#include <stdlib.h>
struct student {
char surname[50];
int age;
char oname[50];
char address[50];
};
void displaystudent(struct student* pStudent);
void inputstudent(struct student* pStudent);
int main() {
struct student aStudent;
inputstudent(&aStudent);
displaystudent(&aStudent);
return 0;
}
void inputstudent(struct student* pStudent){
printf("Enter the surname: ");
scanf("%s", pStudent->surname);
printf("Enter the other name: ");
scanf("%s", pStudent->oname);
printf("Enter the age: ");
scanf("%d", &pStudent->age);
printf("Enter the address: ");
scanf("%s", pStudent->address);
}
void displaystudent(struct student* pStudent)
{
printf("Surname: %s \n", pStudent->surname);
printf("Oname: %s \n", pStudent->oname);
printf("Age: %d \n", pStudent->age);
printf("Address: %s", pStudent->address);
}
You seem to want the changes that you make to the structure variable s inside inputstudent() to be reflected back to the original variable. In that case you need to pass the address of the variable to the function instead of its value.
If you pass the value of s to the function instead of its address, a new copy of s would be made inside inputstudent() and the values would be read into this copy while the s in main() remains unchanged.
To solve this you give inputstudent() a pointer to the s in main() and make inputstudent() use this address while reading the data. In this way the changes made for the variable in inputstudent() will be reflected back to the s in main().
Call the function like
inputstudent(&s);
And to access members of a structure variable using a pointer to it, you use the -> operator instead of the . operator.
void inputstudent(struct student *s){
printf("Enter the surname: ");
scanf("%s",s->surname);
printf("Enter the other name: ");
scanf("%s",s->oname);
printf("Enter the age: ");
scanf("%d",&s->age);
printf("Enter the address: ");
scanf("%s",s->address);
}
Also, an address possibly involves white spaces in which scanf() won't do. You could use fgets() for that.
There are basically two causes for your problem.
Function declarations don't have any parameters.
The structure is passed by value instead of reference to inputstudent function.
You can solve both of them by changing the function prototypes in both declaration and definition to
void displaystudent(struct student s);
void inputstudent(struct student &s);
You can't use struct student s as parameter in inputstudent(). It is just a value copy.
You should use pointer as parameter.
As:
void inputstudent(struct student* s)
{...}
int main(){
struct student s;
inputstudent(&s);
displaystudent(s);
return 0;
}
I'm learning about structs and memory allocation.
One of the things i found out by studying was that there is not a way to see if a block of memory was allocated correctly.
I think it's working properly, but i was getting ready to read about linked lists and got all confused again.
I ask this, because on linked lists, i have seen:
typedef LIST* Lint;
int main(){
Lint *lint;
}
and by defining the type of class like this on my code:
typedef CLASS* t;
int main(){
t class; // WITHOUT THE * BEFORE class
}
it worked! I thought it would be ok, to give the definition like this. To me makes sense, the class is now a pointer to a type (type ie. CLASS);
So, am i on the right track or this working was pure luck?
The code structure sucks, but i'm still learning :)
typedef struct student {
char name[50];
int grade;
} TURMA;
typedef CLASS* t;
void showS(struct student i){
printf("Name of Student: %s \n Grade of Student: %d\n", i.name, i.grade);
}
void insert(struct student *i,int k){
char n[100]; int q=0;
printf("Define name of student %d\n", k+1); scanf("%s", n);
printf("Define the grade of %s\n", n); scanf("%d", &q);
strcpy(i->name,n);
i->grade = q;
}
int main()
{
t class;
int total,plus,i;
printf("Define number of total students: \n"); scanf("%d", &total);
class = (struct student*) malloc(total*(sizeof(CLASS)));
for(i=0; i<total; i++){
insert(&class[i], i);
}
printf("\n\nThis is the complete class: \n");
for(i=0; i<total; i++){
showS(class[i]);
}
printf("(Total size after malloc: %lu) Add more students (Int)\n",sizeof(*turma)); scanf("%d", &plus);
class = realloc(class, plus*sizeof(CLASS));
free(class);
printf("(Total size after malloc: %lu)", sizeof(*class));
return 0;
}
It is really hard to tell exactly what you are trying to accomplish. I looks like you are trying to create a singly-linked-list out of struct student with a typedef of struct student to TURMA. That's about where the useful information ends. Attempting to declare typedef CLASS* t; makes no sense. The compiler doesn't know what CLASS is. Guessing what you were attempting, the following is what flows from your code.
note: I added one function flush_stdin to empty stdin so you wouldn't have pesky newline characters left in the buffer. I also changed the scanf format string to prevent leaving newlines following your reading of character strings. Take a look below, and I'll look at your latest additions.
Also note in your code, you cannot free (class); then expect to take sizeof(*class)) -- that is undefined behavior.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXN 100
typedef struct student {
char name[50];
int grade;
} TURMA;
typedef TURMA* t;
void flush_stdin ()
{
int c = 0;
while ((c = getchar()) != '\n' && c != EOF);
}
void showS (TURMA i)
{
printf("Name of Student: %s \n Grade of Student: %d\n", i.name, i.grade);
}
void insert (t i, int k)
{
char n[MAXN] = {0}; int q=0;
printf("Define name of student %d\n", k+1); scanf ("%[^\n]%*c", n);
printf("Define the grade of %s\n", n); scanf("%d", &q); flush_stdin();
strcpy(i->name,n);
i->grade = q;
}
int main()
{
t class;
int total,plus,i;
printf("Define number of total students: \n"); scanf("%d", &total); flush_stdin();
class = malloc (total * sizeof *class);
if (!class) {
fprintf (stderr, "error: virtual memory exhausted.\n");
exit (EXIT_FAILURE);
}
for (i=0; i<total; i++){
insert (&class[i], i);
}
printf("\n\nThis is the complete class: \n");
for (i=0; i<total; i++){
showS (class[i]);
}
printf("(Total size after malloc: %lu) Add more students (Int)\n", sizeof *class * total);
scanf("%d", &plus); flush_stdin();
TURMA *turma = realloc (class, plus * sizeof *turma);
if (!turma) {
fprintf (stderr, "error: virtual memory exhausted.\n");
exit (EXIT_FAILURE);
}
free (class);
printf("(Total size after realloc: %lu)\n", sizeof *turma * (total + plus));
free (turma);
return 0;
}
Output
$ ./bin/llclass
Define number of total students:
2
Define name of student 1
John James
Define the grade of John James
8
Define name of student 2
Jill James
Define the grade of Jill James
9
This is the complete class:
Name of Student: John James
Grade of Student: 8
Name of Student: Jill James
Grade of Student: 9
(Total size after malloc: 112) Add more students (Int)
2
(Total size after realloc: 224)
Right after scanning the second element, the program crashes. It is not able to go to the scanning of the third element(i.e. grade). Need help, in figuring out what I am wrong wrong.
#include<stdio.h>
#include<stdlib.h>
#define NUM 2
typedef struct STUDENT
{
int ID;
char *name;
char *grade;
};
int main ()
{
int i;
struct STUDENT *s;
s = (struct STUDENT*)malloc(NUM*sizeof(struct STUDENT*));
printf("Enter Student's ID, Name and Grade:\n");
for(i=0;i<NUM;i++)
{
printf("Enter ID:\n");
scanf("%d", &(s+i)->ID);
printf("Enter Student Name:\n");
scanf("%s", (s+i)->name);
printf("Enter Grade:\n");
scanf("%s", (s+i)->grade);
printf("\n");
}
printf("\nInformation of the student's are:\n");
for(i=0;i<NUM;i++)
{
printf("Student ID = %d\n", (s+i)->ID);
printf("Student Name = %s\n", &(s+i)->name);
printf("Student grade = %c\n", &(s+i)->grade);
printf("\n");
}
return 0;
}
You do not allocate memory for grade and name in struct STUDENT. Trying to read input and write it to them produces undefined behavior.
Add the necessary mallocs, for example with a given maximum length STR_MAX:
s[i].name = malloc(STR_MAX);
s[i].grade = malloc(STR_MAX);
See the other answers for further errors.
malloc(NUM*sizeof(struct STUDENT*));
should be
malloc(NUM*sizeof(struct STUDENT));
also, the name and grade are not buffers but pointers. You may need a buffer (char array) or allocate memory for it dynamically.
typedef struct STUDENT
{
int ID;
char *name;
char *grade;
};
Here name and grade character type pointer. so when you malloc structure you also have to malloc name and grade too
struct STUDENT *s; should be declared like this:
STUDENT *s;
No need to cast void * from malloc. Change this line s = (struct STUDENT*)malloc(NUM*sizeof(struct STUDENT*)); to this:
s = malloc(NUM * sizeof(*s));
Instead of this scanf("%d", &(s+i)->ID);, the following may be easier to understand:
scanf("%d", &s[i].ID);
Same here:
printf("Student ID = %d\n", s[i].ID);
Most importantly, what Nabla said.