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;
}
Related
I have two structures. A pointer is assigned to one.
Now I would like to output data previously entered via scanf via a function (outputAddress) with a pointer as a parameter.
It works with the variables via the pointer. But how do I do that with the values from the other structure? How can I output this in the function?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct structPerson
{
char name[30];
char forename[50];
int age;
};
struct structAddress
{
int zip;
char location[35];
char street[40];
int hNumber;
struct structPerson *ptrPerson;
};
void outputAddress(struct structPerson *ptrPerson)
{
printf("\n\nOutput Address: \n");
printf("ptrPerson->name: %s", ptrPerson->name);
printf("\nptrPerson->forename: %s", ptrPerson->forename);
return;
}
int main()
{
struct structPerson person1;
struct structAddress address1;
address1.ptrPerson = &person1;
printf("Location: ");
scanf("%s", &address1.location);
printf("Zip: ");
scanf("%d", &address1.zip);
printf("\nName: ");
scanf("%s", &address1.ptrPerson->name);
printf("Forename: ");
scanf("%s", &address1.ptrPerson->forename);
printf("\nOutput: %d %s %s\n", address1.zip, address1.location, address1.ptrPerson->name);
// strcpy( address1.location, "");
// printf("structAddress1: %d %s\n", address1.zip, address1.location);
outputAddress(&person1);
return 0;
}
In your data model structAddress is associated with a person via the personPtr field. As a result, Address is a main data struct. If I understand your intention correctly, you want to print info about the person and then his/her address.
For this you need to do a couple of changes. Firstly, you should pass the Address struct to the print function, because it has all information available, including the pointer to the person. Secondly, you should access your person information using the pointer: ptrAddress->ptrPerson-><field>. Here is an example.
void outputAddress(struct structAddress *ptrAddress)
{
printf("\n\nOutput Address: \n");
// use ptrAddress->ptrPreson to accesss person information
printf("ptrPerson->name: %s", ptrAddress->ptrPerson->name);
printf("\nptrPerson->forename: %s", ptrAddress->ptrPerson->forename);
// use ptrAddress-> to access address fields.
printf("\nptrAddress->zip: %d", ptrAddress->zip);
...
return;
}
int main() {
...
outputAddress(&address1); // << use address1 here.
...
}
Your datamodel is probably broken anyway. The address struct has a pointer to a person, but it often makes more sense to have it the other way around.
What's the Error in this ?
I tried taking input using arrow operator.
#include <stdio.h>
typedef struct{
char name[100];
int salary;
}emp;
void inp(emp *e){
printf("enter name : ");
gets(e->name);
printf("enter salary : ");
scanf("%d", e->salary);
}
int main() {
emp *e1,*e2;
inp(e1);
inp(e2);
printf("%s , %d\n", e1->name,e1->salary);
printf("%s , %d\n", e2->name,e2->salary);
return 0;
}
I tried putting & and even giving inp function as emp but it doesn't work.
It just asking me 1st employee name. dat's it!
Not even printing Enter salary.
What changes should I make?
Your struc have been created wrong. So i changed your code like this to make it clear. I also did use getchar() function so you can call fget() function multiplie times. I guess it does work like you wish.
#include <stdio.h>
struct Emp{
char name[100];
int salary;
};
void func(struct Emp *e){
printf("enter name : ");
fgets(e->name, sizeof(e->name), stdin);
printf("enter salary : ");
scanf("%d", &e->salary);
getchar();
}
int main() {
struct Emp e1,e2;
func(&e1);
func(&e2);
printf("\n%s , %d", e1.name,e1.salary);
printf("\n%s , %d", e2.name,e2.salary);
return 0;
}
emp *e1,*e2;
creates two pointers that point to nothing... They are just uninitialized pointers. They are not pointing to any valid memory. So when you dereference them using -> your program is likely to crash.
You need to allocate memory using, e.g. malloc
Like
e1 = malloc(sizeof *e1);
you should choose another better name for your function first, inp is already a function name in c, see this: https://cboard.cprogramming.com/c-programming/21255-ansi-c-function-inp-outp-inp-inpw.html
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 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.
Im suppose to print student details from the user into a student structure and I don't understand why when I compile with linux terminal, there is no entry or output. Please hep me, I'm new here.
This is my code:
#include <stdio.h>
#include <stdlib.h>
struct student
{
char *name;
int id;
char enroll;
};
int main()
{
struct student john;
john.name = "John Smith";
john.id = 12345678;
john.enroll = 'D';
}
void getStudent(struct student *john)
{
printf("Type the name of the student: ");
john->name = malloc(100);
fgets(john->name, 100, stdin);
printf("\nType the student number: ");
scanf("%d", &(john->id));
printf("\nType the student enrollment option (D or X): ");
scanf("%c", &(john->enroll));
return;
}
void printstudent(struct student john)
{
printf("Student name: %s\n", john.name);
printf("Student number: %d\n", john.id);
printf("Student enrollment option: %c\n", john.enroll);
return;
}
You need to call your functions from main (or from any function that needs them). Writing a function (declaring it) doesn't actually execute it.
int main()
{
foo(); // execute foo (call it)
}
void foo()
{
// do stuff
}
Your functions are functions like printf() and scanf() and have to also be called to be used.
You need to invoke the functions you have defined, from the main.
Add this statement inside the main function.
printstudent(john);