#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char firstName[20];
char lastName[20];
int id;
char gender[10];
int monthOfBirth;
int dayOfBirth;
int yearOfBirth;
} HealthProfile;
void setName(HealthProfile *HP) {
char firstName;
char lastName;
printf("Enter your first and last name: ");
scanf("%s" "%s", &firstName, &lastName);
HP->firstName = firstName;
HP->lastName = lastName;
}
void setID(HealthProfile *HP) {
int id;
printf("Enter ID: ");
scanf("%d", &id);
HP->id = id;
}
void setGender(HealthProfile *HP) {
char gender;
// HealthProfile hp;
// strcpy(hp.gender, &gender);
printf("Enter your gender: ");
scanf("%s", &gender);
HP->gender = gender;
}
void setBD(HealthProfile *HP) {
int monthOfBirth;
int dayOfBirth;
int yearOfBirth;
printf("Enter your month of birth, day of birth and year of birth: ");
scanf("%d" "%d" "%d", &monthOfBirth, &dayOfBirth, &yearOfBirth);
HP->monthOfBirth = monthOfBirth;
HP->dayOfBirth = dayOfBirth;
HP->yearOfBirth = yearOfBirth;
}
int main(){
// pointer declared to HealthProfile structure
HealthProfile *HP;
// pointer initialized using malloc
HP = (HealthProfile*) malloc(sizeof(HealthProfile));
// Calls various functions
setID(HP);
setGender(HP);
setName(HP);
setBD(HP);
// Creates your profile
printf("Creating your Health Profile! \n");
printf("Profile created for: %s\n", HP->firstName);
printf("Lastname: %s\n", HP->lastName);
// prints ID
printf("ID: %d\n", HP->id);
printf("Gender: %s\n", HP->gender);
printf("Month of birth: %d\n", HP->monthOfBirth);
printf("day of birth: %d\n", HP->dayOfBirth);
printf("year of birth: %d\n", HP->yearOfBirth);
}
What I am trying to do is assign HP to a string but I get this error.
array type 'char [10]' is not assignable
HP->gender = gender;
(same error with first and last name of course) So I searched online and found out that char can't be assigned and strcpy should be used instead. As you can see by my failed attempt in the gender function.
Can someone help me fix my errors? Thanks
As you've discovered, you can't assign directly to an array. For strings in particular, you would need to use strcpy to copy a string from one array to another.
Additionally, gender is a single character, not an array. So passing &gender to scanf will cause the function to treat it as a pointer to a sequence of characters instead of a pointer to just one, resulting in the function writing past the memory bounds of the variable.
You can fix this by making gender an array of the proper size:
void setGender(HealthProfile *HP) {
char gender[10];
printf("Enter your gender: ");
scanf("%s", gender);
strcpy(HP->gender, gender);
}
Or you could skip the temp variable entirely and write directly to the field in the struct:
void setGender(HealthProfile *HP) {
printf("Enter your gender: ");
scanf("%s", HP->gender);
}
And do the same for reading firstname and lastname.
char gender; - gender is not an array. It is only one object of type char.
Thus, HP->gender = gender; does not work because gender does not decay to a pointer to char like an array would do.
Edit it to char gender[10].
actually I think that you should not using Assignment for string and array .Instead you should use strcpy and include string.h library.
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.
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;
}
This here is a small portion of a larger program I need to create to enter songs and their info into a database. I am new to using structs and my professor hasnt showed us yet on how to pass structs into functions and then using those inside main. I am also not supposed to use pointers yet. I get many errors when compiling and I'm not sure where to start.
#include <stdio.h>
typedef struct mp3song_struct {
char title[40];
char artist1[20];
char artist2[20];
char artist3[20];
int datemonth;
int dateday;
int dateyear;
char genre[10];
}mp3song;
void populate(mp3song totalsongs[30]);
int main() {
struct mp3song totalsongs[30];
populate(mp3song totalsongs);
}
void populate(mp3song totalsongs[30]){
int i = 0;
for(i = 0; i < 5; ++i){
printf("Enter song title: \n");
scanf("%c", &totalsongs[i].title);
printf("Enter Artists(If no more than 1 enter \"none\")");
printf("Enter artist: \n");
scanf("%c", &totalsongs[i].artist1);
printf("Enter artist: \n");
scanf("%c", &totalsongs[i].artist2);
printf("Enter artist: \n");
scanf("%c", &totalsongs[i].artist3);
printf("Ente date mm/dd/yyyy\n");
printf("Enter month: \n");
scanf("%d", &totalsongs[i].datemonth);
printf("Enter day: \n");
scanf("%d", &totalsongs[i].dateday);
printf("Enter year: \n");
scanf("%d", &totalsongs[i].dateyear);
printf("Enter genre: \n");
scanf("%c", &totalsongs[i].genre);
}
}
There are several problems in your code. You can declare int populate(struct mp3song, struct mp3song totalsongs[30]); as void populate(struct mp3song, struct mp3song totalsongs[30]); since you are not returning an integer.
mp3song is not an array so it cannot be subscripted like &mp3song[i]. In fact populate function cannot receive struct mp3song as it is a type not value. So modify populate function line int populate(struct mp3song totalsongs[30]); and then replace all occurances of &mp3song[i] with &totalsongs[i] and you will be able to take input in the array.
mp3song is a structure name not structure variable
you need to declare a variable of that structure type to pass a structure.
example:
struct definition
struct <struct_name>{
Struct elements;
}<struct variable>;
struct <struct_name> <struct_variable>;
In your case
you can pass only variable not struct_name
struct mp3song totalsongs[30];
populate(totalsongs[30]);
function definition
<return_type int or void> populate(struct mp3song totalsongs[30]);
Now you can access structure elements with variable name totalsongs inside the function.
modifed code of yours
#include <stdio.h>
typedef struct mp3song {
char title[40];
char artist1[20];
char artist2[20];
char artist3[20];
int datemonth;
int dateday;
int dateyear;
char genre[10];
};
void populate(struct mp3song totalsongs[30]);
int main() {
struct mp3song totalsongs[30];
populate(totalsongs);
}
void populate(struct mp3song totalsongs[30]){
int i = 0;
for(i = 0; i < 5; ++i){
printf("Enter song title: \n");
scanf("%s", &totalsongs[i].title);
printf("Enter Artists(If no more than 1 enter \"none\")");
printf("Enter artist: \n");
printf("TITLE: : %s \n",totalsongs[i].title);
scanf("%c", &totalsongs[i].artist1);
printf("Enter artist: \n");
scanf("%c", &totalsongs[i].artist2);
printf("Enter artist: \n");
scanf("%c", &totalsongs[i].artist3);
printf("Ente date mm/dd/yyyy\n");
printf("Enter month: \n");
scanf("%d", &totalsongs[i].datemonth);
printf("Enter day: \n");
scanf("%d", &totalsongs[i].dateday);
printf("Enter year: \n");
scanf("%d", &totalsongs[i].dateyear);
printf("Enter genre: \n");
scanf("%c", &totalsongs[i].genre);
}
}
I have the following code. In the struct definition, I try to ask user to enter employee's first and last name. But when I run this exe, it exit after the title is entered. Any suggestions?
#include<stdio.h>
#include<string.h>
#define NUMEMPS 10
struct Employee {
char *firstname;
char *lastname;
char *title;
int salary;
};
int main()
{
struct Employee* stuff = malloc(NUMEMPS* sizeof *stuff);
int n,i;
for (n=0; n<NUMEMPS;n++)
{
printf("Please enter number %d Employee's Last name:", n);
fflush(stdout);
gets(stuff[n].lastname);
if (strlen(stuff[n].lastname) == 0)
break;
printf("Please enter number %d Employee's first name:", n);
fflush(stdout);
gets(stuff[n].firstname);
printf("Please enter number %d Employee's title:", n);
fflush(stdout);
gets(stuff[n].title);
printf("Please enter number %d Employee's salary:", n);
fflush(stdout);
scanf("%d", &stuff[n].salary);
getchar();
}
for (i = 0;i<n;i++)
{
printf("{%s,%s,%s,%d}\n",
stuff[i].lastname,
stuff[i].firstname,
stuff[i].title,
stuff[i].salary);
}
return 0;
}
The three char* members of the structure are pointers, so no space is allocated to hold any data.
With the current struct you'd have to do three more allocs for the data:
struct Employee* stuff = malloc(NUMEMPS* sizeof *stuff);
stuff->firstname = malloc(101);
stuff->lastname = malloc(101);
stuff->title = malloc(101);
What you probably want is something like:
struct Employee {
char firstname[101];
char lastname[101];
char title[101];
int salary;
};
Also, though as an aside, you must check your malloc calls for a NULL return.
This code:
struct Employee {
char *firstname;
char *lastname;
char *title;
int salary;
};
...
struct Employee* stuff = malloc(NUMEMPS* sizeof *stuff);
only allocates enough room to store a single struct Employee, that is: three pointers and an integer. There's no storage for the character strings pointed to.
Instead, consider malloc()ing each of the constituent character data and assigning to stuff->firstname (et al), or modify the declaration of struct Employee to include character arrays.
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.