i've created a struct "Employee"
#define MAX_SIZE 20
typedef struct Employee{
char name[MAX_SIZE];
int s;
int e;
} employee_s;
and i need to create an array of 2 employees and ask the user to initialize them, nothing i try seem to work,
void main()
{
int i, s, e;
char name[10];
Employee* e[3];
*e = (Employee*)malloc(sizeof(Employee)*ARR_SIZE);
for(i=0; i < 3; i++)
{
fflush(stdin);
puts("Please enter Employee's name:");
scanf("%c",&name);
*e[i]->name = name;
puts("Please enter Employee's salary:");
scanf("%d",&s);
*e[i]->s= s;
puts("Please enter Employee's experience:");
scanf("%d",&e);
*e[i]->e=e;
}
}
p.s: i dont have to use dynamic allocation,
what do i do wrong?
thank you!
There are several errors here:
Employee is not a valid type. struct Employee is, and so is employee_s.
e is defined in multiple places
When reading in name, use %s (for a string), not %c (for a char)
Your employee array is defined as an array of pointers. That's probably not what you want. You just need an array. No call to malloc either.
Never fflush(stdin). It's undefined behavior.
In your scanf calls, put a space as the first character in the string. That will allow any newlines to be passed over.
The result:
int main()
{
int i;
employee_s e[3];
for(i=0; i < 3; i++)
{
puts("Please enter Employee's name:");
scanf(" %s",&e[i].name);
puts("Please enter Employee's salary:");
scanf(" %d",&e[i].s);
puts("Please enter Employee's experience:");
scanf(" %d",&e[i].e);
}
for(i=0; i < 3; i++) {
printf("emp %d: name=%s, sal=%d, exp=%d\n", i, e[i].name, e[i].s, e[i].e);
}
}
You've got your declaration backward. This:
typedef struct Employee{
char name[MAX_SIZE];
int s;
int e;
} employee_s;
declares a type named employee_s to be equivalent to struct Employee, and furthermore declares struct Employee. You appear to want this, instead:
typedef struct employee_s {
char name[MAX_SIZE];
int s;
int e;
} Employee;
In this case you can omit employee_s from that if you wish; perhaps that would be less confusing.
Moreover, you are going about your allocation in a very strange way, especially since you don't require dynamic allocation. Why not just do this:
Employee e[3];
? Then you can (and should) skip malloc() altogether. You will then refer to the members of the array elements via the form e[0].name, etc..
You can do this easily without dynamic memory allocation as follows.
#include <stdio.h>
#define MAX_SIZE 20
typedef struct Employee{
char name[MAX_SIZE];
int s;
int e;
} employee_alias;
int main(void) {
int i;
employee_alias e[3];
for(i=0; i < 3; i++)
{
puts("Please enter Employee's name:");
scanf("%s",e[i].name);
puts("Please enter Employee's salary:");
scanf("%d",&e[i].s);
puts("Please enter Employee's experience:");
scanf("%d",&e[i].e);
printf("Entered Data\n");
printf("Name : %s\n",e[i].name);
printf("Salary : %d\n",e[i].s);
printf("Experience : %d\n",e[i].e);
}
return 0;
}
Related
#include <stdio.h>
int i, n;
struct add_stock
{
char fullname[30];
int stocks;
char com_name[30];
int shares;
float price;
float total;
int totalmoney;
} add;
int main()
{
printf("Enter full name : ");
scanf(" %[^\n]s", add.fullname);
printf("Enter the no. of stocks you want to purchased : ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter the name of the company : ");
scanf(" %[^\n]s", add[i].com_name);
printf("Enter the no. of shares you want to purchased : ");
scanf("%d", &add[i].shares);
printf("Enter the price of each share : ");
scanf("%f", &add[i].price);
add.total = add.shares * add.price;
printf("Toatl money invested in this stock : ");
scanf("%f", &add[i].total);
}
printf("Total money invested : ");
scanf("%d", add.totalmoney);
return 0;
}
In question it's add_stock , not add stock , i write like this becoz it's not accepting question.
So, i get error for "add" saying subscripted value is neither array nor pointer nor vector.
To declare an array of strucuture, you need to define the variable as below,
struct add_stock
{
char fullname[30];
int stocks;
char com_name[30];
int shares;
float price;
float total;
int totalmoney;
} add[20];
this makes the add as an array of add_stock elements.
then you can access it as, add[0].total, add[1].price and so on.
If you want to declare an array that need to be having dynamic number of elements, you can do so as below.
struct add_stock* arStock;
//allocate memory to hold 10 elements
arStock = (add_stock*)malloc( 10 * sizeof(struct add_stock));
arStock[0]->total=10; //access it with ->, instead of .
This code is about 'struct' in C..
I created a struct with the properties name,roll etc.. By using the for-loop I let the user to create the struct objects. they are named as student,employee, faculty
the problem is the objects are created. But I can use them only inside the for-loop. If I want to get the value of all names in main function, it doesn't work. How can I solve it?How do i print all names in the code in only one loop
what will be the logic
#include<stdio.h>
#include<conio.h>
struct student
{
int std;
char fee[90]; //Collect Data of students
int rollno;
char name[15];
char sub[100];
};
main()
{
int x;
printf("******Enter the total number of Student from HOD*******:\n");
scanf("%d",&x);
struct student a[x];
for(int i=0;i<x;i++)
{
printf("\nEnter Rollno:\t");
scanf("%d",&a[x].rollno);
printf("\nEnter name:\t");
scanf("%s",&a[x].name);
printf("\nIs Fee Submitted:\t");
scanf("%s",&a[x].fee);
printf("\nEnter Subject name:\t");
scanf("%s",a[x].sub);
}
printf("\n****Display All Student names****");
for(int i=0;i<x;i++)
{
printf("\n%s",a[x].name);
}
//Faculty
struct faculty
{
char Fname[100];
char Sname[100];
};
int y;
printf("\n\n********Please HOD enter the total faculty members********\n");
scanf("%d",&y);
struct faculty b[y];
for(int j=0;j<y;j++)
{
printf("\nEnter Faculty Member Name:\t");
scanf("%s",&b[y].Fname);
printf("\nEnter their Subjects:\t");
scanf("%s",&b[y].Sname);
}
printf("\n****Display all Faculty Member Name****");
for(int j=0;j<y;j++)
{
printf("\n%s",b[y].Fname);
}
// Employes
struct employes
{
char ename[100];
char rank[100];
};
int z;
printf("\n\n********please HOD enter the total no of Employes*******:\n");
scanf("%s",&z);
struct employes c[z];
for(int j=0;j<y;j++)
{
printf("\nEnter the Employe name:\t");
scanf("%s",&c[y].ename);
printf("\n and enter their ranks:\t");
scanf("%s",&c[y].rank);
}
printf("\n****Display all Employe names****");
for(int j=0;j<y;j++)
{
printf("%s\n",c[y].ename);
}
}
#include<stdio.h>
#include<conio.h>
struct student
{
int std;
char fee[90];
int rollno;
char name[15];
char sub[100];
};
main()
{
int x;
printf("******Enter the total number of Student from HOD*******:\n");
scanf("%d",&x);
struct student a[x];
for(int i=0;i<x;i++)
{
printf("\nEnter Rollno:\t");
scanf("%d",&a[x].rollno);
printf("\nEnter name:\t");
scanf("%s",&a[x].name);
printf("\nIs Fee Submitted:\t");
scanf("%s",&a[x].fee);
printf("\nEnter Subject name:\t");
scanf("%s",a[x].sub);
}
printf("\n****Display All Student names****");
for(int i=0;i<x;i++)
{
printf("\n%s",a[x].name);
}
struct faculty
{
char Fname[100];
char Sname[100];
};
int y;
printf("\n\n********Please HOD enter the total faculty members********:\n");
scanf("%d",&y);
struct faculty b[y];
for(int j=0;j<y;j++)
{
printf("\nEnter Faculty Member Name:\t");
scanf("%s",&b[y].Fname);
printf("\nEnter their Subjects:\t");
scanf("%s",&b[y].Sname);
}
printf("\n****Display all Faculty Member Name****");
for(int j=0;j<y;j++)
{
printf("\n%s",b[y].Fname);
}
struct employes
{
char ename[100];
char rank[100];
};
int z;
printf("\n\n********Please HOD enter the total no of Employes*******:\n");
scanf("%d",&z); //You used %s instead of %d
struct employes c[z];
for(int j=0;j<z;j++) //You used wrong variable 'y' here
{
printf("\nEnter the Employe name:\t");
scanf("%s",&c[z].ename); //You used wrong variable 'y' here
printf("\nEnter their ranks:\t");
scanf("%s",&c[z].rank); //You used wrong variable 'y' here
}
printf("\n****Display all Employe names****");
for(int j=0;j<z;j++) //You used wrong variable 'y' here
{
printf("\n%s",c[z].ename); //You used wrong variable 'y' here
}
}
Errors:
Wrong format specifier used in taking integer input in number of Employees.
Wrong loop variable used in all loops of Employee.
Now this code is working. I've pointed out the errors in the comments also.
The loop increases i from 0 to some other value x.
(lets say x is 5 for this example)
So i has values 0, 1, 2, 3....
But regardless, you only put data into one element of the array: 5
And you keep overwriting that same element over and over again.
And 5 isn't even a valid index!! The valid indicies are 0, 1, 2, 3, 4.
5 is one-past the end of the array!
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 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;
}
I am having trouble making an array of structures. I want to store data regarding multiple students and take input using the execution of the program. Then output the memory address of persons name with highest marks.
I tried getting to know the answers on similar issues on site, to no help.
The code I have written is
the struct
struct student{
char name;
int marks;
};
and the function is
int num,max = 0,i;
printf("Number of students?\n");
scanf("%d", &num);
struct student* students = (struct student*)malloc (num* (sizeof(struct student)));
for (int x = 0; x < num; x++)
{
printf("Enter Name\n");
scanf("%c" , &students[x].name);
printf("Enter Marks\n");
scanf ("%d" , &students[x].marks);
}
for (i = 1; i < num; i++)
{
if (students[max].marks<students[i].marks)
{
max = i;
}
}
printf("The Memory Add for %c is %p\n", students[max].name , &students[max].name );
It is a part of menu driven program. It goes into a weird loop after line 5 in function code. And i can't create a doubly linked list for the same.
Edit 1
These are the changes i made to struct and func
struct student{
char name[20];
int marks;
};
void memadd(){
int num,max = 0,i, mark;
printf("Number of students?\n");
scanf("%d", &num);
struct student* students = (struct student*)malloc (num* (sizeof(struct student)));
for (int x = 0; x < num; x++)
{
printf("Enter Name\n");
scanf("%s" , &students[x].name);
printf("Enter Marks\n");
scanf ("%d" , &mark);
students[x].marks = mark;
}
for (i = 1; i < num; i++)
{
if (students[max].marks<students[i].marks)
{
max = i;
}
}
printf("The Memory Add for %s is %p\n", students[max].name , &students[max].name );
It is giving an array at input of the name. "format specifies type 'char ' but the argument has
type 'char ()[20]'"
How do I make the format to be char * [20]?
Edit 2
The final working code after correcting the char name to being a character array
And issue with scanning of names.
struct student{
char name[20];
int marks;
};
int num,max = 0,i, mark;
printf("Number of students?\n");
scanf("%d", &num);
struct student* students = (struct student*)malloc (num* (sizeof(struct student)));
for (int x = 0; x < num; x++)
{
printf("Enter Name\n");
scanf("%19s" , students[x].name);
printf("Enter Marks\n");
scanf ("%d" , &mark);
students[x].marks = mark;
}
for (i = 1; i < num; i++)
{
if (students[max].marks<students[i].marks)
{
max = i;
}
}
printf("The Memory Add for %s is %p\n", students[max].name , &students[max].name );
However, what if I wish to print the address in Hex numbers? or the one that am getting is hex already.?
Because I got an output of The Memory Add for XYZ is 0x7fb340c03928
The problem is with the student name being a char and
scanf("%c" , &students[x].name);
What happens is, you read in the number of students with
scanf("%d", &num);
Now you have read num, but there is still a newline in the input buffer.
Then you try to read a character with %c, but this reads the remaining newline.
When you change the student's name to a character array, e.g.
struct student{
char name[20];
int marks;
};
and read the name with
scanf("%19s" , students[x].name);
it will skip the remaining whitespace/newline and read the name as it should.