Structures for C programming - c

Here is the current code. For averaging gradesa from 3 students. Underneath the code are the errors im facing. Was able to work them down from 25 to 4.
Visual studio is saying i have an unidentified expression E0029, E0020, C2065, C2109
dont believe im using pointers as we were told not use them. Read the error codes and looked them but cant determine where im falling short.
Thank you in advanced.
#include <stdio.h>
#define N 5
struct student {
char firstName[50];
int roll;
float marks[3];
}s[N];
typedef struct {
char firstName[50];
int roll;
float marks[3];
}student_t;
int main() {
int i;
double total = 0;
double marks_avg ;
student_t personA, personB, SMCstudent[N];
SMCstudent->marks[0] = 99;
personA= { "Daniel",10 {100,98,90}
};
printf("Enter information of student:\n");
//storing
for (i = 0;i < N;++i); {
s[i].roll = i + 1;
printf("\nFor all number %d,\n", s[i].roll);
printf("Enter first name:");
scanf_s("%s", &s[i].marks);
}
printf("Enter 3 marks");
for (int j = 0; j < 3; j++) {
printf("enter grade\n");
scanf_s("%f", s[i].marks[j]);
scanf_s("%f", & array[i]);
}
for (i = 0; i < N; i++) {
total += s[i].marks[2];
}
marks_avg = total / N;
printf("average grade for 5 students is %f\n\n", marks_avg);
printf("displaying information:\n\n");
return 0;
}

#RetiredNinja claims that you can only do a structure assignment during initialization.
This is simply not true.
You need to specify the type name as well, but this code is valid:
personA = (student_t){ "Daniel", 10, {100.f,98.f,90.f} };
This is assigning a "compound literal" to a structure.
(l-value personA is the structure, and the right side, (student_t){...} is the compound literal)
Example, working code:
#include <stdio.h>
typedef struct {
char firstName[50];
int roll;
float marks[3];
}student_t;
int main(void) {
student_t personA;
personA= (student_t){ "Daniel",10, {100.f,98.f,90.f} };
printf("%s(%d): %.2f %.2f %.2f", personA.firstName, personA.roll,
personA.marks[0], personA.marks[1], personA.marks[2]);
return 0;
}

Related

I am having hard time taking pointer structure as a function's parameter in C. I am a beginner and I am confused

#include<stdio.h>
struct create
{
int a;
int b;
int c;
float total;
};
struct create Create[3];
float givename(struct create* storage[3]);
int main()
{
for(int j = 0; j<4; ++j)
{
printf("Input a[%d]:", j+1);
scanf("%d", &Create[j].a);
printf("Input b[%d]:", j+1);
scanf("%d", &Create[j].b);
printf("Input c[%d]:", j+1);
scanf("%d", &Create[j].c);
float sum = givename(&Create);
printf("%f", sum);
}
}
float givename(struct create* storage[3])
{
for(int i = 0; i<4; ++i)
{
storage[i]->total = storage[i]->a + storage[i]->b + storage[i]->c;
return storage[i]->total;
}
}
This is something I wrote and of course it doesn't work, it might seem stupid to elitist C programmers but a help would be appreciated. I wanted to take an input into array of structure and then use it inside a function that has been called by reference.
Please tell me can someone help me show what I am misunderstanding with the logic ?
The function
float givename(struct create* storage[3])
takes an array of pointers to struct create, you are sending the address of an array of struct create. If you want an array of pointers to struct create, do it like this:
struct create * array[3];
array[0] = & Create[0];
array[1] = & Create[1];
array[2] = & Create[2];
Plus, this function stops during the first iteration, because of the return.
Array's size is 3, you're looping 4 times.
Your main needs a return value;
If you wanted to pass the whole array to givename (an array of struct create, not pointers), you don't need to since Create is global;
For each iteration in the first loop (3 after fixing), you iterate the whole array, I doubt this is what you wanted to do.
The following version prompts to fill 3 struct create, computes the total for each (and stores it), and prints it.
Is this what you wanted to do ?
#include<stdio.h>
#include <stdlib.h>
struct create
{
int a;
int b;
int c;
float total;
};
struct create Create[3];
float givename(struct create * storage);
int main()
{
for(int j = 0; j < 3; ++j)
{
printf("Input a[%d]:", j+1);
scanf("%d", & Create[j].a);
printf("Input b[%d]:", j+1);
scanf("%d", & Create[j].b);
printf("Input c[%d]:", j+1);
scanf("%d", & Create[j].c);
float sum = givename(& Create[j]);
printf("%f\n", sum);
}
return EXIT_SUCCESS;
}
float givename(struct create * storage)
{
storage->total = storage->a + storage->b + storage->c;
return storage->total;
}
echo 1 2 3 4 5 6 7 8 9 | yourProgram
>> Input a[1]:Input b[1]:Input c[1]:6.000000
>> Input a[2]:Input b[2]:Input c[2]:15.000000
>> Input a[3]:Input b[3]:Input c[3]:24.000000
What you wanted to achieve is quite unclear, and the naming doesn't help, I recommend you to give better names:
struct create doesn't describe what is stored inside
Consider compiling with -Wall -Wextra -Werror.
Your givename() (seems like a bad name) currently only processes one struct as it returns inside the loop. And the way you are calling it after each input of 3 integers it would only process a struct (the first struct each time), and not the array of structs. To process the array of structs you could call it after you got all the input - outside the loop taking input. This shows a version processing during the loop for each struct and then a version processing after the loop with all input.
#include<stdio.h>
struct create
{
int a;
int b;
int c;
float total;
};
struct create Create[3];
float givename(struct create *storage);
float calculate_totals(struct create storage[3]);
float get_grand_total(struct create [3]);
int main()
{
for(int j = 0; j<3; ++j)
{
printf("Input a[%d]:", j+1);
scanf("%d", &Create[j].a);
printf("Input b[%d]:", j+1);
scanf("%d", &Create[j].b);
printf("Input c[%d]:", j+1);
scanf("%d", &Create[j].c);
float sum = givename(&Create[j]);
printf("%f\n", sum);
}
get_grand_total(Create);
/* calculate all totals after input */
for(int j = 0; j<3; ++j)
{
printf("Input a[%d]:", j+1);
scanf("%d", &Create[j].a);
printf("Input b[%d]:", j+1);
scanf("%d", &Create[j].b);
printf("Input c[%d]:", j+1);
scanf("%d", &Create[j].c);
}
float grand_total = calculate_totals(Create);
printf("grand total = %f\n",grand_total);
}
float givename(struct create *storage)
{
storage->total = storage->a + storage->b + storage->c;
return storage->total;
}
float get_grand_total(struct create storage[3])
{
float grand_total = 0;
for (int i = 0; i < 3; i++)
{
grand_total += storage[i].total;
}
printf("grand total sum=%f\n",grand_total);
return grand_total;
}
float calculate_totals(struct create storage[3])
{
float grand_total = 0;
for(int j = 0; j<3; ++j)
{
storage[j].total = storage[j].a + storage[j].b + storage[j].c;
printf("total for struct %d=%f\n",j+1,storage[j].total);
grand_total += storage[j].total;
}
return grand_total;
}

how can i solve segmentation error in terminal message?

I wrote a simple program to take names and numbers from the user and store it in an array, then compare between each cell until it reach the maximum grade then it displays it. The problem is that when it run it shows a message (segmentation fault (Core dump)). I really don't know what my mistake is.
#include <stdio.h>
int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", & n);
char name[n];
float score[n];
for (int i = 0; i < n; i++) {
printf("\nEnter the name of Student: ");
scanf("%s", & name[i]);
printf("\nEnter the score: ");
scanf("%f", & score[i]);
}
float max;
int index;
max = score[0];
index = 0;
for (int i = 1; i < n; i++) {
if (max < score[i]) {
max = score[i];
index = i;
}
}
printf("\nHighest mark scored is %f by student %s", name[index], score[index]);
}
1- you use user input to define the size of an array (wrong)
-- array in c has static size so you must define it's size before the code reach the compiling stage(use dynamic memory allocation instead)
2- scanf("%s", & name[I]); you want to save array of char and save the address at the name variable but name it self not a pointer to save address it's just of char type (wrong)
-- you need pointer to save the address of every name so it's array of pointer and a pointer to allocate the address of the array to it so it's a pointer to poiner and define max size of word if you define size the user input exceed it will produce an error
3- finally you exchanged the %f,%s in printf
#include <stdlib.h>
#include <stdio.h>
#define SIZE_OF_WORD 10
int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", & n);
char **name=(char**)malloc((sizeof(char*)*n));
for (int i = 0; i < n; i++) {
name[i]=(char*)malloc((sizeof(char)*SIZE_OF_WORD));
}
float *score=(float*)malloc((sizeof(float)*n));
for (int i = 0; i < n; i++) {
printf("\nEnter the name of Student: ");
scanf("%s", name[i]);
printf("\nEnter the score: ");
scanf("%f", & score[i]);
}
float max;
int index;
max = score[0];
index = 0;
for (int i = 1; i < n; i++) {
if (max < score[i]) {
max = score[i];
index = i;
}
}
printf("\nHighest mark scored is %s by student %.0f\n", name[index],score[index]);
}

Inputting errors in structure pointer code

#include <stdio.h>
typedef struct book
{
int bid;
char bname[50];
} bok;
typedef struct student
{
int roll;
char sec;
char name[50];
bok *issue;
} stud;
int main()
{
int n;
printf("enter no. of students\n");
scanf("%d", &n);
stud s[n];
printf("enter names,section and roll no. of %d students\n", n);
for (int i = 0; i < n; i++)
{
scanf("%s", &s[i].name);
scanf("%c", &s[i].sec);
scanf("%d", &s[i].roll);
}
int m, temp;
printf("enter no. of books\n");
scanf("%d", &m);
bok s1[m];
printf("enter book id and book names of %d books\n", m);
for (int i = 0; i < m; i++)
{
scanf("%d\n", &s1[i].bid);
scanf("%s\n", &s1[i].bname);
}
printf("assign book id to students.\n");
for (int i = 0; i < n; i++)
{
printf("assign id for roll %d\n", s[i].roll);
scanf("%d\n", s[i].issue);
}
int info;
printf("enter roll no. of student to get his/her information and book assigned to him\n ");
scanf("%d\n", &info);
for (int i = 0; i < n; i++)
{
if (s[i].sec == info)
printf("name:%s \nsection:%c \nbook assigned:%s\n", s[i].name, s[i].sec, *s[i].issue);
}
}
my code is not showing any compilation error but it does not give required output.my question is Create 2 two structure array Student and Book by the name S and B. And link the students with their respective books.
Print the books issued by a particular student.
Do not forget the brackets in order to assign user's input to the corresponding struct member:
for (int i = 0; i < n; i++)
{
scanf("%s", &(s[i].name));
scanf("%c", &(s[i].sec));
scanf("%d", &(s[i].roll));
}
and here you need to assign the input to bid, you cannot set an integer for book:
scanf("%d\n", &(s[i]->issue.bid));
or you wil get a segfault.

Sort by using Structure's arrays

So I want to sort the list so that i can give them their position according to their grades but it's not working.
It is Showing error like : incompatible types when assigning to type char from type struct info.
p.s : I am trying to do this sorting using Structures.
#include <stdio.h>
#define SIZE 3
struct info {
char name[20];
int number;
double grade;
};
int main(void) {
struct info list[SIZE];
int i, j;
char temp;
int avg;
for (i = 0; i < SIZE; i++) {
printf("Enter your name : ");
scanf("%s", list[i].name);
printf("Enter your number : ");
scanf("%d", & list[i].number);
printf("Enter your grade : ");
scanf("%lf", & list[i].grade);
}
for (i = 0; i < SIZE; i++) {
printf("Name : %s Student Number : %d Grade : %f", list[i].name,
list[i].number, list[i].grade);
printf("\n");
}
for (i = 0; i < SIZE; i++) {
for (j = i + 1; j < SIZE; j++) {
if (list[j].grade > list[i].grade) {
temp = list[j];
list[j] = list[i];
list[i] = temp;
}
}
}
for (i = 0; i < SIZE; i++) {
printf("%d st Position : Name : %s Student Number : %d Grade : %f ",i,
list[i].name, list[i].number, list[i].grade);
printf("\n");
}
avg = 0;
for (i = 0; i < SIZE; i++)
avg += list[i].grade;
avg = avg / 3;
printf("Average is %d", avg);
getch();
return 0;
}
errors are in the following code:
for(i=0;i<SIZE;i++) {
for(j=i+1;j<SIZE;j++) {
if(list[j].grade>list[i].grade) {
temp=list[j];
list[j]=list[i];
list[i]=temp;
}
}
}
You assign a type char with name temp and try to assign a struct to it. Instead create a struct temp and then sort your array of structs.
#include <stdio.h>
#define SIZE 3
struct info { // use typedef struct info instead
char name[20];
int number;
double grade;
};
int main(void) {
struct info list[SIZE]; // allows you to write info list[size]
int i, j; // do not initialize loop variables outside of their loops unless you need to(makes it easier to read the loop statements/spot mistakes)
char temp; // you need to use a type info, not char e.g. info temp
I can not compile it myself at the moment, so please let us know in the comments if you have any further questions.

Confusion with Structures and how to store values with pointer in C

This question may be annoying, but I am trying to write code the way that I can most easily mentally process it and at this point it is without calling functions. I am rewriting my professors example code into my own, but am having a problem with what to store it into? He uses a pointer, but I just don't know how/where to declare it.
My apologies if this question is incorrectly worded. I am one of those people who just doesn't 'get it' when it comes to programming unfortunately.
My Professors:
#include <stdio.h>
#include <stdlib.h>
/* Program that computes the average salary of the employees with an age equal or greater
than x, x is passed as a parameter to the main function. Employee is a structure with two
fields: age and salary. */
struct employee {
int age;
float salary;
};
void readValues(struct employee *EMP, int n ) {
int i;
for(i=0; i<n; i++) {
printf("Employee %i\n", i+1);
printf("\tAge: ");
scanf("%i", &EMP[i].age);
printf("\tSalary: ");
scanf("%f", &EMP[i].salary);
}
}
float getAvg(struct employee *EMP, int minAge, int n ) {
int i, nE = 0;
float sum=0;
for(i=0; i<n; i++) {
if(EMP[i].age >= minAge) {
sum = sum + EMP[i].salary;
nE = nE + 1;
}
}
return sum/nE;
}
int main(int argc, char *argv[]) {
int x, n;
struct employee E[100];
if (argc<3) {
printf("Error: Some parameters missing.\n");
return -1;
}
x = atoi(argv[1]);
n = atoi(argv[2]);
readValues(E, n);
float avg = getAvg(E, x, n);
printf("Avg. Salary = %.2f\n", avg);
return 0;
}
My attempt:
#include <stdio.h>
#include <stdlib.h>
#define minage 20
struct employee{
int age;
float salary;
};
int main()
{
struct employee emp = {0};
int i, n, numb=0, sum=0, avg;
printf("How many employees do you have today?\n");
scanf("%i", n);
for(i=0; i<n; i++)
{
printf("Employee %i", i+1);
printf("Age:\n");
scanf("%i", &emp[i].age);
printf("Salary:\n");
scanf("%f", &emp[i].salary);
}
if (emp[i].age >= minage)
{
for(i=0, i<n; i++){
sum = sum + emp[i].salary
numb = numb + 1
}
}
avg = sum / numb;
printf("The average salary is %i\n", avg);
}
Refer the below Code: Comments Inline
#include <stdio.h>
#include <stdlib.h>
#define minage 20
struct employee{
int age;
float salary;
};
int main()
{
/* Use array of struct to store the employee record. */
struct employee emp[100];
int i, n, numb=0, sum=0;
float avg = 0; /* If avg is of type int then you will loose the precision when finding the average */
printf("How many employees do you have today?\n");
scanf("%i",&n); /* Use `&` when using scanf to read value into integer*/
for (i = 0; i < n; i++) {
printf("Employee %i", i+1);
printf("Age:\n");
scanf("%i", &emp[i].age);
printf("Salary:\n");
scanf("%f", &emp[i].salary);
}
/* Your professor is calculating avg salary only if age >= minage.
* But in your code your are trying to check if the last employee age is
* >= minage only after which calculating the avg salary of all employee's*/
for (i = 0; i < n; i++) {
if (emp[i].age >= minage) {
sum = sum + emp[i].salary;
numb = numb + 1;
}
}
/* Make sure to check whether numb != 0, else divide by zero exception
* when there are no employee's with age greater than 20 (minage) */
if (numb)
avg = sum / numb;
printf("The average salary is %.2f\n", avg);
/* return 0; when return type of main() is int.
* If not required then change to void main()*/
return 0;
}
Also as your professor is initializing minage from user input. In your code it is hard coded to a fixed number 20.
Try to read the minage from user as you did to get the number of employee's.

Resources