I have to declare a vector with the "struct" type which, for every n students, it creates a value for the group that student belongs to (which is like a counter), their names and their grades.
The program has to output the name of the students with the highest grade found in these groups. I have to allocate the vector on the heap (I only know the theoretical explanation for heap, but I have no idea how to apply it) and I have to go through the vector using pointers.
For example if I give n the value 4, there will be 4 students and the program will output the maximum grade together with their names as shown here.
This will output Ana 10 and Eva 10.
I gave it a try, but I have no idea how to expand it or fix it so I appreciate all the help I can get with explanations if possible on the practical application of heap and pointers in this type of problem.
#include <stdio.h>
#include <stdlib.h>
struct students {
int group;
char name[20];
int grade;
};
int main()
{
int v[100], n, i;
scanf("%d", n);
for (i = 0; i < n; i++) {
v[i].group = i;
scanf("%s", v[i].name);
scanf("%d", v[i].grade);
}
for (i = 0; i < n; i++) {
printf("%d", v[i].group);
printf("%s", v[i].name);
printf("%d", v[i].grade);
}
return 0;
}
Here I was just trying to create the vector, nothing works though..
It appears, int v[100]; is not quite what you want. Remove that.
You can follow either of two ways.
Use a VLA. After scanning the value of n from user, define the array like struct students v[n]; and carry on.
Define a fixed size array, like struct students v[100];, and use the size to limit the loop conditions.
That said,
scanf("%d", n); should be scanf("%d", &n);, as %d expects a pointer to integer type argument for scanf(). Same goes for other cases, too.
scanf("%s", v[i].name); should better be scanf("%19s", v[i].name); to avoid the possibility of buffer overflow by overly-long inputs.
Even though you are asking for the number of students (groups) using scanf, you hardcoded the upper bound of this value using v[100]. So, I passed your input variable n (the number of students) to malloc in order to allocate the space you need for creating an array of n students.
Also, I used qsort to sort the input array v where the last element would be the max value. Here qsort accepts an array of structs and deference the pointers passed to the comp function to calculate the difference of the comparison.
Finally, I printed the sorted array of structs in the last loop.
#include <stdio.h>
#include <stdlib.h>
struct students {
int group;
char name[20];
int grade;
};
int comp(const void *a, const void *b)
{
return ((((struct students *)a)->grade > ((struct students *)b)->grade) -
(((struct students *)a)->grade < ((struct students *)b)->grade));
}
int main()
{
int n;
printf("Enter number of groups: ");
scanf("%d", &n);
printf("\n");
struct students *v = malloc(n * sizeof(struct students));
int i;
for(i = 0; i < n; i++)
{
v[i].group = i;
printf("\nName: ");
scanf("%s", v[i].name);
printf("Grade: ");
scanf("%d", &v[i].grade);
}
qsort(v, n, sizeof(*v), comp);
for(i = 0; i < n; i++)
{
printf("Group %d, Name %s, grade %d\n", v[i].group, v[i].name, v[i].grade);
}
return (0);
}
You need to replace the standalone array v[100], with an array of structs referencing your structure:
struct students v[100];
However, if you want to use malloc to allocate memory on the heap, you will need to do something like this:
struct students *students = malloc(n * sizeof(struct students));
/* Check void* return pointer from malloc(), just to be safe */
if (students == NULL) {
/* Exit program */
}
and free the requested memory from malloc() at the end, like this:
free(students);
students = NULL;
Additionally, adding to #Sourav Ghosh's answer, it is also good to check the return value of scanf(), especially when dealing with integers.
Instead of simply:
scanf("%d", &n);
A more safe way is this:
if (scanf("%d", &n) != 1) {
/* Exit program */
}
With all this said, your program could look something like this:
#include <stdio.h>
#include <stdlib.h>
#define NAMESTRLEN 20
typedef struct { /* you can use typedef to avoid writing 'struct student' everywhere */
int group;
char name[NAMESTRLEN+1];
int grade;
} student_t;
int
main(void) {
int n, i;
printf("Enter number of students: ");
if (scanf("%d", &n) != 1) {
printf("Invalid input.\n");
exit(EXIT_FAILURE);
}
student_t *students = malloc(n * sizeof(*students));
if (!students) {
printf("Cannot allocate memory for %d structs.\n", n);
exit(EXIT_FAILURE);
}
for (i = 0; i < n; i++) {
students[i].group = i;
printf("Enter student name: ");
scanf("%20s", students[i].name);
printf("Enter students grade: ");
if (scanf("%d", &(students[i].grade)) != 1) {
printf("Invalid grade entered.\n");
exit(EXIT_FAILURE);
}
}
printf("\nStudent Information:\n");
for (i = 0; i < n; i++) {
printf("Group: %d Name: %s Grade: %d\n",
students[i].group,
students[i].name,
students[i].grade);
}
free(students);
students = NULL;
return 0;
}
Related
I'm incredibly new to this and have a school assignment I have to write a gradebook program that uses a custom struct to hold student IDs and grades. I have been trying unsuccessfully for days to figure out why it will not print properly, or when it does print (after a lot of shifting things around) it only prints the second set of input.
The gradebook.h section is the custom structure.
// gradebook.h
struct gradeID
{
int id;
char grades[25];
};
// Gradebook.h is a header file to define
// a global structure.
#include "gradebook.h"
#include <stdio.h>
#include <stdlib.h>
void sort(struct gradeID *, int);
int main(void)
{
// Variables and structure definitions
int ctr;
char contInput;
int i;
struct gradeID grade;
struct gradeID *identifier;
int *temps;
// Allocates 10 integers worth of memory for the program to use.
// If there is not enough memory, the program will print an error
// statement and terminate the program.
temps = (int *) malloc(10 * sizeof(int));
if (temps == 0)
{
printf("Not enough memory!\n");
exit(1);
}
// Prints basic instructions for the program
printf("\t\tGradebook Recorder\n");
printf("Input student IDs and grades.\n");
printf("These will be sorted by ID and printed.\n");
/* Creates a for loop that will continue until the program
hits the designated number of array elements. For the sake
of expediency, I have set this amount to 10, but it can be
changed as necessary.*/
for(i = 0; i < 10; i++)
{
printf("Input student ID:\n");
scanf(" %d", &grade.id);
printf("Input grade:\n");
scanf(" %s", grade.grades);
// This allows early exit of the program
printf("Do you have more grades to enter?\n");
printf("Y/N\n");
scanf(" %c", &contInput);
if(contInput == 'N' || contInput == 'n')
{
printf("Finalizing and printing input-\n\n");
break;
}
ctr++;
}
printf("Grades Sorted by Student ID:\n\n");
printf("\tStudent ID: Student Grade: \n");
for(i = 0; i < ctr; i++)
{
printf("\t%d", grade.id );
printf("\t%s", grade.grades);
}
identifier[i] = grade;
return(0);
free(temps);
}
void sort(struct gradeID identifier[], int counter)
{
int inner;
int outer;
struct gradeID temp;
// Loops for sorting
for(outer = 0; outer < counter - 1; ++outer)
{
for(inner = outer + 1; inner < counter; ++inner)
{
if(identifier[inner].id < identifier[outer].id)
{
temp = identifier[inner];
identifier[inner] = identifier[outer];
identifier[outer] = temp;
}
}
}
return;
}
The pointer identifier is uninitialized
struct gradeID *identifier;
So this statement
identifier[i] = grade;
independent on the value of i invokes undefined behavior.
In this for loop
for(i = 0; i < 10; i++)
{
printf("Input student ID:\n");
scanf(" %d", &grade.id);
printf("Input grade:\n");
scanf(" %s", grade.grades);
// This allows early exit of the program
printf("Do you have more grades to enter?\n");
printf("Y/N\n");
scanf(" %c", &contInput);
if(contInput == 'N' || contInput == 'n')
{
printf("Finalizing and printing input-\n\n");
break;
}
ctr++;
}
you are entering new data in the same object grade of the structure type. So the new data overrides the previous data stored in the object.
Moreover the variable ctr was not initialized
int ctr;
So this statement in the above for loop
ctr++;
also invokes undefined behavior.
The variable temps that points to a dynamically allocated array
temps = (int *) malloc(10 * sizeof(int));
is not used.
This statement
free(temps);
never gets the control because before it there is the return statement
return(0);
free(temps);
What you need is to define an array of the type struct gradeID as for example
struct gradeID grades[10];
and fill it with values.
I am trying to access different elements in my dynamic struct array however I can't seem to access any other element in the array besides the first.
C file
#include <stdio.h>
#include <stdlib.h>
#include "tuples.h"
void createTuple();
int main() {
createTuple();
return 0;
}
void createTuple(){
int numOfTup;
printf("How many tuples would you like to create:\n");
scanf(" %d", &numOfTup);
tuple_t *tuples;
tuples = malloc(numOfTup * sizeof(char) * sizeof(int) * 3);
if (tuples == NULL){
printf("Memory allocation failed");
exit(EXIT_FAILURE);
}
for (int j = 0; j < numOfTup; ++j) {
printf("Enter an identifier for the Tuple: \n");
scanf(" %c", &tuples[j].identifier);
printf("TUPLE: %c\n",tuples[j].identifier);
for (int i = 0; i < 4; ++i) {
printf("Enter the value for the tuple (C:I:I:I)\n");
if (i == 0) {
scanf(" %c", &tuples[j].val0);
} else if (i == 1) {
scanf(" %d", &tuples[j].val1);
} else if (i == 2) {
scanf(" %d", &tuples[j].val2);
} else if (i == 3) {
scanf(" %d", &tuples[j].val3);
}
}
}
}
Header file for the struct
#ifndef TASK2_TUPLES_H
#define TASK2_TUPLES_H
struct tuple{
char identifier[100];
char val0;
int val1;
int val2;
int val3;
};
typedef struct tuple tuple_t;
#endif //TASK2_TUPLES_H
I can't seem to access the struct at tuples[j] because whenever I try to run it it only saves the first set of elements.
Also whenever inputting the identifier the compiler skips the loop and does not allow me to enter any elements into the struct.
Thanks.
For starters, the statement:
tuples = malloc(numOfTup * sizeof(char) * sizeof(int) * 3);
//always ==1 why? why?
Should look more like:
tuples = malloc(numOfTup * sizeof(*tuples));
and:
scanf(" %c", &tuples[j].identifier);//wrong format specifier for string
^^^ ^ //and address of ( & ) operator not needed for string.
Should be:
scanf("%s", tuples[j].identifier);
^^ ^
There are several issues with your code:
You allocate nowhere near enough memory. If your tuple identifier is 100 chars, you should allocate at least 101 * sizeof(char) + 3*sizeof(int) bytes of memory. In practice, this might not suffice because the compiler might pad the struct to better align with memory. Thus, the real size might be greater. The safe thing to do is to allocate sizeof(tuple_t) bytes
Your scanf function to read the identifier reads a char, not a string. use %s to read string. Also, scanf expects pointers to already allocated objects of the type specified by their corresponding format specifier, in our case, %s is a string, so the type should be char *. Thus, the parameter should be tuples[j].identifier, rather than &tuples[j].identifier
Overall:
#include <stdio.h>
#include <stdlib.h>
#include "tuples.h"
void createTuple();
int main() {
createTuple();
return 0;
}
void createTuple(){
int numOfTup;
printf("How many tuples would you like to create:\n");
scanf(" %d", &numOfTup);
tuple_t *tuples;
tuples = malloc(numOfTup * sizeof(tuple_t));
if (tuples == NULL){
printf("Memory allocation failed");
exit(EXIT_FAILURE);
}
for (int j = 0; j < numOfTup; ++j) {
printf("Enter an identifier for the Tuple: \n");
scanf("%s", tuples[j].identifier);
printf("TUPLE: %s\n",tuples[j].identifier);
for (int i = 0; i < 4; ++i) {
printf("Enter the value for the tuple (C:I:I:I)\n");
if (i == 0) {
scanf(" %c", &tuples[j].val0);
} else if (i == 1) {
scanf(" %d", &tuples[j].val1);
} else if (i == 2) {
scanf(" %d", &tuples[j].val2);
} else if (i == 3) {
scanf(" %d", &tuples[j].val3);
}
}
}
}
I am trying to make a two dimensional array in a struct using pointer since I am new to c and get quite confuse in the topic of pointer. Help please!
struct course
{
char *coursecode;
char *coursesession[5];
};
int main()
{
int n = 0;
int numSession = 0;
struct course *main = malloc(sizeof(struct course));
printf("Enter the course code and the session in this order:");
scanf("%s", main->coursecode);
printf("Enter the number of session required:");
scanf("%d", &numSession);
for (int i = 0; i < numSession; ++i)
{
printf("Enter the session code (M1...):");
scanf("%s", main->coursesession[i]);
}
++n;
}
You've declared coursecode to be a pointer to char, but you need to allocate space for it, which you can do with malloc.
And you've declared coursesession to be an array of 5 pointers to char. You need to allocate space for all 5 pointers, again with malloc.
Alternatively, you could declare both of them as arrays, e.g.
struct course
{
char coursecode[100];
char coursesession[5][100];
};
This declares coursecode to be an array of 100 char, and coursesession to be an array of 5 arrays of 100 char. Obviously you could adjust the 100 to whatever you need, but the storage size would be fixed regardless.
You can modify code like this
#include <stdio.h>
#include<stdlib.h>
struct course
{
char *coursecode;
char *coursesession[5];
};
int main()
{
int n,i = 0;
int numSession = 0;
struct course main;
main.coursecode = (char *)malloc(100*sizeof(char));
printf("Enter the course code and the session in this order:");
scanf("%s", main.coursecode);
printf("Enter the number of session required:");
scanf("%d", &numSession);
for (i = 0; i < numSession; ++i)
{
printf("Enter the session code (M1...):");
main.coursesession[i] = (char *)malloc(100*sizeof(char));
scanf("%s", main.coursesession[i]);
}
++n;
free(main.coursecode);
for (i = 0; i < numSession; ++i){
free(main.coursesession[i]);
}
}
I cooked a code for a program that asks the user to fill in information about a person (ReadDate/ReadPerson), then it asks for the range of people the user wants to print, and the function prints these people. (PrintRange)
I don't understand why the program is not working; it's stuck on the point when it should print the person... it's means there is probably a problem in either PrintPerson or PrintDate, or in the way I am calling these functions.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
int day, month, year;
} Date;
typedef struct{
char *first_name, *last_name;
int id;
Date birthday;
} Person;
void ReadDate(Date *a)
{
printf("Enter the day: ");
scanf("%d", &a->day);
printf("Enter the month (1-12): ");
scanf("%d", &a->month);
printf("Enter the year: ");
scanf("%d", &a->year);
}
void ReadPerson(Person *b)
{
char temp_first_name[21];
char temp_last_name[21];
printf("Enter the first name: ");
gets(temp_first_name);
b->first_name = (char*)malloc(strlen(temp_first_name)+1);
strcpy(b->first_name,temp_first_name);
//need to check malloc (later)
printf("Enter the last name: ");
gets(temp_last_name);
b->last_name = (char*)malloc(strlen(temp_last_name)+1);
strcpy(b->last_name, temp_last_name);
//need to check malloc (later)
printf("Enter the id number: ");
scanf("%d",&b->id);
printf("Enter the birthday:\n");
ReadDate(&b->birthday);
}
int ReadAllDate (Person *b)
{
//Person* b;
int count=1;
char choice;
printf("Would you like to enter a person?(y,n)\n");
choice = getchar();
while(choice == 'y')
{
b = (Person*)malloc(1 * sizeof(Person));
getchar();
ReadPerson(b);
printf("Done!\n");
count++;
getchar();
printf("Would you like to add a person?(y,n)\n");
choice = getchar();
}
count--;
printf("The number of entered persons is %d\nBye\n", count);
return count;
}
void PrintPerson(Person b)
{
printf("%s %s %d\n", b.first_name, b.last_name, b.id);
}
void PrintDate(Date a)
{
printf("%d // %d // %d\n",a.day,a.month,a.year);
}
void PrintRange(Person *b,int count,int ind1,int ind2)
{
int i;
if (ind1<0 || ind1>ind2 || ind2>count)
{
printf("error! you slip out from the limits of the array.\n");
}
else
{
for (i=ind1; i<=ind2; i++)
{
PrintPerson(*(b+i));
PrintDate((b+i)->birthday);
}
}
}
int main(int argc, const char * argv[])
{
Person* b;
int count;
int ind1, ind2;
count = ReadAllDate(b);
printf("insert the first index (the smaller): ");
scanf("%d", &ind1);
printf("insert the second index (the bigger): ");
scanf("%d", &ind2);
PrintRange(b, count, ind1, ind2);
}
The problem is that nowhere you are actually creating an array of Person objects. The function ReadAllDate() never changes the value of the variable b in main(). Instead, for every person you read in, it allocates memory for it, and stores the pointer to that Person in the local variable b in ReadAllDate(). Every time it does it, it forgets the previous value of b.
In main(), the value of b is unitinialized all the time. When you are trying to print persons, it will most likely crash or print garbage.
I see other issues with your code:
Don't use gets(), always use fgets(). The former can write past the end of the buffer you are providing.
Don't do malloc(strlen(...))+strcpy(), use strdup().
Start with count = 0, that way you don't need the count-- in ReadAllDate(). As a computer programmer, it's best to count from zero instead of one.
Write b[i] instead of *(b+i), and b[i].birthday instead of (b+i)->birthday.
I'm working on a homework assignment and I've hit a brick wall. I think I have all of the code that I need, I just need to get the program to compile. The object of the assignment is
Create a structure to hold student names and averages. The structure should contain a first name, last name and an integer grade average.
Then:
Write a program that will do the following:
1.) Create an array of pointers to these student structures.
2.) Prompt the user for names and averages.
3.) After you get the student’s information use malloc to provide the memory to store the information.
4.) Place the address of the student, returned by malloc, into the pointer array.
5.) AFTER the user indicates there are no more students:
Search the data entered and find the highest and lowest grade
average.
a)Print the name and grade for the highest grade
b)Print the name and grade for the lowest grade
c)Print the average of all grades entered
Here is my code:
#include "stdafx.h"
#include <string.h>
#include <stdlib.h>
#define SIZE 25
int enterStudents (int ePointArray[SIZE]);
void searchData (int *sPointArray, int *sHigh, int *sLow);
int calculateAvg (int, int *avgPointArray);
void printData (int, int *pHigh, int *pLow);
struct student
{
char firstName[20];
char lastName[20];
int average;
};
int main()
{
int pointArray[SIZE], high[3], low[3];
int i = 0, studentCounter, avgGrade;
for (i = 0; i < SIZE; i++)
pointArray[i] = 0;
studentCounter = enterStudents(pointArray);
searchData(pointArray, high, low);
avgGrade = calculateAvg(studentCounter, pointArray);
printData(avgGrade, high, low);
return 0;
}
int enterStudents (int ePointArray[SIZE])
{
char tempFname[20], tempLname[20], yesNo[2] = "y";
int tempAvg, counter = 0;
int *studPtr;
struct student aStud={"\0", "\0", 0};
while( counter < SIZE && strcmp(yesNo, "y")==0)
{
printf(" Enter first name: ");
scanf("%s", tempFname);
printf(" Enter last name: ");
scanf("%s", tempLname);
printf(" Enter grade average:");
scanf("%d", tempAvg);
strcpy(aStud.firstName, tempFname);
strcpy(aStud.lastName, tempLname);
aStud.average = tempAvg;
studPtr = malloc(sizeof(struct student));
ePointArray[counter] = *studPtr;
counter++;
printf("/n");
printf(" Do you have more students? yes or no:");
scanf("%s", yesNo);
}
return counter;
}
void searchData (int sPointArray[SIZE], int sHigh[3], int sLow[3])
{
int searchCounter = 0;
while( searchCounter = 0)
{
if( *sPointArray[searchCounter].average > *sPointArray[searchCounter+1].average)
{
sHigh[0] = &sPointArray[searchCounter].firstName;
sHigh[1] = &sPointArray[searchCounter].lastName;
sHigh[2] = &sPointArray[searchCounter].average;
}
if( *sPointArray[searchCounter].average < *sPointArray[searchCounter+1].average)
{
sLow[0] = &sPointArray[searchCounter].firstName;
sLow[1] = &sPointArray[searchCounter].lastName;
sLow[3] = &sPointArray[searchCounter].average;
}
searchCounter++;
}
}
int calculateAvg( int totalStudents, int avgPointArray[SIZE])
{
int sum = 0;
int avgCounter;
double overallAvg;
for( avgCounter = 0; avgCounter < totalStudents; avgCounter++)
sum = sum + *avgPointArray[avgCounter].average;
overallAvg = sum/totalStudents;
return overallAvg;
}
void printData (int pAverage, int pHigh[3], int pLow[3])
{
printf(" Highest Grade: %s %s %d", pHigh[0], pHigh[1], pHigh[3]);
printf("/n");
printf(" Lowest Grade: %s %s %d", pLow[0], pLow[2], pLow[3]);
printf("/n");
printf(" Average Grade: %d",pAverage);
}
The main chunk of problems come from the searchData function. In the if statements, every occurrence of *sPointArray and &sPointArray is underlined in red and the error reads
"Error: expression must have class type"
The same thing also happens in the calculateAvg function with *avgPointArray in the for loop. I know that the error is a fairly common problem for noobie C programmers (i.e myself) and that it generally has to do with writing the code as a function instead of a statement or something like that, but I can't for the life of me find where I have went wrong. Any help would be highly appreciated. I've been working at this for so long my vision is blurring.
Also, for anyone who solves this in like two seconds and wants proof that I'm a true idiot, there is an error in the enterStudents function where it says StudPtr = malloc(sizeof...). The error shows under the assignment symbol and says
"Error: a value of type "void*" cannot be assigned to an entity of type "int*".
I understand this concept in theory, but some advice for how to fix it would be highly appreciated.
Thank you in advance for any help.
You declare the sPointArray as an array of integers, but use it as an array of structures.