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);
}
}
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.
#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.
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'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.
I am trying to write simple program to collect data for certain number of students and output it in the end. After I enter data for one student, my program crashes.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
typedef struct Student Student;
struct Student{
char name[20];
char lastname[20];
int age;
};
main() {
int i;
int n;
scanf("%d",&n);
Student *pStudents = NULL;
pStudents = (Student*)malloc(n*sizeof(Student));
for(i=0;i<n;i++) {
printf("Enter the students name: \n");
scanf("%s",(pStudents+i)->name);
printf("Enter lastname: \n");
scanf("%s",(pStudents+i)->lastname);
printf("Enter age: \n");
scanf("%d",(pStudents+i)->age);
}
for(i=0;i<n;i++) {
printf("%s",(pStudents+i)->name);
printf("%s",(pStudents+i)->lastname);
printf("%d",(pStudents+i)->age);
}
}
Thanks in advance.
scanf("%d",(pStudents+i)->age);
the argument of scanf must be of a pointer type.
Change (pStudents+i)->age to &(pStudents+i)->age.