Using pointers with structures to pass data to functions - c

This is a program for a class project. It is suppose to be able to create and edit structures. The CreatRec function works fine. For the ModifyRec I am trying to send it the array by pointers in order to avoid having to "copy" the data. However, I am having trouble getting it to actually change the array. ATM The line at the bottom (gr[change].lastname= *info;) is not working at all. I really have no clue what I am doing wrong here.
#include "stdafx.h"
#include <string.h>
#include <stdlib.h>
struct student{
int recordname;
char lastname[10];
char firstname[10];
float math;
float english;
float science;
};
//prototypes
int menu();
struct student CreatRec(int);
void ModifyRec(struct student*);
void main()
{
int option, j;//option will be for users menu choice, j makes for loop work for creatrec
struct student grades[10];
j = 0;
option=Menu();
if (option == 1)
for (j = 0; j<10; j++)
(grades[j + 0]) = CreatRec(j);
else if (option==2)
ModifyRec(grades);//dont need & is smart bc array
printf("%s",grades[0].lastname);//This line is checking to see if ModifyRec actaully worked
//free(grades);2
while (1);
}
int Menu()
{
int choi;
printf("Please choose one of the following options.\n 1) Create New Student Records.\n 2) Modify an Existing Student Record\n");
printf(" 3) Print a New Sutdent Record.\n 4) Quit\n");
scanf("%d", &choi);
return choi;
}
struct student CreatRec(int i)
{
struct student qr;
//qr = (struct student*)malloc(sizeof(struct student)*6);
printf("RecordNum %i\n", i);
printf("Please enter last name-->");
scanf("%s", &qr.lastname);
printf("Please enter first name-->");
scanf("%s", &qr.firstname);
printf("Please math grade-->");
scanf("%f", &qr.math);
printf("Please english grade-->");
scanf("%f", &qr.english);
printf("Please science grade-->");
scanf("%f", &qr.science);
return qr;
}
void ModifyRec(struct student gr[])
{
int change;
char feild[10], info[10];
printf("Which record would you like to change?\n");
scanf("%d", &change);
rewind(stdin);
printf("Which feild would you like to edit?\n");
scanf("%s", &feild);
rewind(stdin);
printf("Enter info\n");
scanf("%s", &info);
if (!strcmp("lastname", feild))
gr[change].lastname= *info;//NOT WORKING
}

First of all I do not see a great sense in expression grades[j + 0] of statement
for (j = 0; j<10; j++)
(grades[j + 0]) = CreatRec(j);
These statements
printf("Please enter last name-->");
scanf("%s", &qr.lastname);
printf("Please enter first name-->");
scanf("%s", &qr.firstname);
have to be substituted for
printf("Please enter last name-->");
scanf("%s", qr.lastname);
printf("Please enter first name-->");
scanf("%s", qr.firstname);
And this statement
if (!strcmp("lastname", feild))
gr[change].lastname= *info;//
has to be substituted for
if (!strcmp("lastname", feild))
strcpy( gr[change].lastname, info );

gr[change].lastname is a char array, not a pointer. You can't reassign it. In this case, you probably ought to do scanf("%s", gr[change].lastname); and skip char info[10] altogether.

Related

Program doesnt show the things I want it to show

I am currently trying to write a program in which when the user selects "1" It will ask him the number of students.It will then create a dynamic array and store all of their information in there.However I am running into the problem where when I try to print the information of the students my program just spews out numbers and letters.Here is the program:
#include <stdio.h>
#include <stdlib.h>
typedef struct student{
int id;
char name[50];
char surname[50];
int semester;
float grade;
}student;
int main()
{
int x,std,i;
x=0;
student** info;
while (x!=8)
{
printf("1. Initialize student list\n2. Add a student record\n3. Delete a student record\n4. Display a student record by student surname\n5. Display students passed\n6. Display students failed\n7. Display all student records\n8. Exit");
printf("\nYour choice: ");
scanf("%d",&x);
if (x==1)
{
printf("How many new students? ");
scanf("%d",&std);
struct student come[std];
struct student *ptr = NULL;
ptr=come;
info = (student**)malloc(std*sizeof(student*));
for(i = 0; i < std; i++){
printf("Enter detail of student #%d\n", (i + 1));
ptr->id=i+1;
printf("Enter first name: ");
scanf("%s", ptr->name);
printf("Enter last name: ");
scanf("%s", ptr->surname);
printf("Enter semester: ");
scanf("%d", &ptr->semester);
printf("Enter grade: ");
scanf("%f", &ptr->grade);
ptr++;
}
}
else if (x==2)
{
/* code */
}
else if (x==3)
{
/* code */
}
else if (x==4)
{
/* code */
}
else if (x==5)
{
/* code */
}
else if (x==6)
{
}
else if (x==7)
{
struct student come[std];
struct student *ptr = NULL;
ptr=come;
for(i = 0; i < std; i++){
printf("%d", ptr->id);
printf("%s", ptr->name);
printf("%s", ptr->surname);
printf("%d", ptr->semester);
printf("%f", ptr->grade);
printf("\nn");
ptr++;
}
}
}
At first I used come[i].grade for all of them (name,id,etc) but it would return something along the lines of 19845241814DNva1280.000000 . Then I added the "&" before it but it gave me 6422088oIv4DNva64221920.000000. The last thing i tried is going with ptr->id but no luck.It just returned to me 19845241814DNv`a1280.000000. The same thing as the first.
The problem is how you use the pointers. There is no necessary use of a pointer to pointer.
#include <stdio.h>
#include <stdlib.h>
typedef struct student{
int id;
char name[50];
char surname[50];
int semester;
float grade;
}student;
int main()
{
int x,std,i;
x=0;
struct student *ptr = NULL;
while (x!=8)
{
printf("1. Initialize student list\n2. Add a student record\n3. Delete a student record\n4. Display a student record by student surname\n5. Display students passed\n6. Display students failed\n7. Display all student records\n8. Exit");
printf("\nYour choice: ");
scanf("%d",&x);
if (x==1)
{
printf("How many new students? ");
scanf("%d",&std);
ptr = (student*)malloc(std*sizeof(student));
for(i = 0; i < std; i++){
printf("Enter detail of student #%d\n", (i + 1));
ptr[i].id=i+1;
printf("Enter first name: ");
scanf("%s", ptr[i].name);
printf("Enter last name: ");
scanf("%s", ptr[i].surname);
printf("Enter semester: ");
scanf("%d", &ptr[i].semester);
printf("Enter grade: ");
scanf("%f", &ptr[i].grade);
}
}
else if (x==2)
{
/* code */
}
else if (x==3)
{
/* code */
}
else if (x==4)
{
/* code */
}
else if (x==5)
{
/* code */
}
else if (x==6)
{
}
else if (x==7)
{
for(i = 0; i < std; i++){
printf("%d", ptr[i].id);
printf("%s", ptr[i].name);
printf("%s", ptr[i].surname);
printf("%d", ptr[i].semester);
printf("%f", ptr[i].grade);
printf("\n");
}
}
}
}
your fundamental problem is that you create a fresh student table for each command (1 and 7). So in the display command you are displaying n unitialized student records.
You also seem to have got into 'grasping at straws' mode for storing the student records, you have pointers, mallocs, dynamically sized stack arrays, 2 dimensional malloced arrays....
option 1 should malloc an array of students of the correct size. The array pointer should be declared before any of the loop code , so that yiou use the same array all the time
student *info = NULL;
int students=0;
...
while (x!=8){
.....
if(x==1){
....
info = malloc(std*sizeof(student));
}
you now have a correctly sized array . to add a student
scanf("%s", info[students].name);
etc
then `students++` to keep count of the number of active students

How do I repeat entering data in a struct using C?

I'm new to C, and currently trying to practice on some simple codes, and I'm currently stuck with that next one.
After entering the first customer data, and repeat the code... View_customer function fails to show the saved data, and when I try to go to enter a second account data, it fails at the second entry.
#include<stdio.h>
#include<stdlib.h>
typedef struct cust{
char name[60];
int acc_no,age;
char address[60];
char citizenship[15];
double phone;
char acc_type[10];
} cust;
void new_account(int num);
void view_account(int num);
int main()
{
cust customers[10];
char answer;
int n;
int cutomer_number=1;
int cutomer_num2;
printf("Welcome To The program X: \n");
do{
printf("\n How can we serve you today? \n 1.Create a new account \n 2.Print an existing Account info \n ");
scanf("%d",&n);
if (n==1)
{
new_account(cutomer_number);
cutomer_number++;
}else {
printf("Please enter your Cust number: ");
scanf(" %d",&cutomer_num2);
view_account(cutomer_num2);
};
printf("\n Press Y to continue. Press any Key To Exit: ");
scanf(" %c",&answer);
}while (answer == 'Y' || answer == 'y');
return 0;
}
void view_account(int n)
{
cust customers[n];
printf("Your name is %s \n ", customers[n].name);
printf("Your age is %d \n", customers[n].age);
printf("Your address is %s \n", customers[n].address);
printf("Your citizenship is %s \n", customers[n].citizenship);
printf("Your phone number is %f \n", customers[n].phone);
printf("Your account type is %s \n", customers[n].acc_type);
};
void new_account(int n)
{
cust customers[n];
customers[n].acc_no = n;
printf("You are the customer number %d \n", customers[n].acc_no);
printf("Please, Enter your name: ");
scanf("%s", &customers[n].name);
printf("Please, Enter your age:");
scanf(" %d", &customers[n].age);
printf("Please, Enter your address: ");
scanf(" %s", &customers[n].address);
printf("Please, Enter your citizenship: ");
scanf(" %s", &customers[n].citizenship);
printf("Please, Enter your phone number: ");
scanf(" %f", &customers[n].phone);
printf("Please, Enter your account type: ");
scanf(" %s", &customers[n].acc_type);
}
>
Each of your three functions declares its own customers array variable, so each of them has their own memory for the customer data. Moreover, the array of new_account goes out of scope at the end of the function, so you can no longer safely access the data. Because of how C compilers typically work, the customer data is not immediately erased from memory, so your view_account function might still be able to read it, but that is what is called "undefined behavior". Which means it might work, or it might not.
Try to pass down the array from the main function to the other two functions in parameters. Or, to make things simpler at first, you could also turn the local customers variable of main into a global variable.
cust customers[10];
int main(int argc, char *argv[])
{
char answer;
int n;
int cutomer_number=1;
int cutomer_num2;
printf("Welcome To The program X: \n");
...
}
void view_account(int n) {
printf("Your name is %s \n ", customers[n].name);
...
}
void new_acccount(int n)
{
customers[n].acc_no = n;
...
}
Note that there are further issues in your code, like not checking the return value of scanf or overflowing the char arrays of the struct if you enter too many characters (missing bounds and length checking), or being able to enter more than 10 customers and accessing out of bounds of the customers array, or not using customers[0] (because your customer_number starts at 1, but array indices are 0-based). But I will not go into further details here to keep the answer focused.

I have a problem initializing a variable connected to a struct array

I have this project where I have to create a struct array with C language for students' data, and I can't seem to get past this warning by my variable arr_student. The warning says that I have not initialized the variable, and whenever I try to debug it the IDE says that it has a memory error involving where it goes. I want to be able to declare it and use it as a way to get to the variables created in my struct array. If anyone knows what I could be missing, that would be greatly appreciated!
#include <stdio.h>
#include <string.h>
#define numero 2 //This number is the limiter for the number of students
struct Student
{ //Define struct array with student information
char id[50];
char gpa[50];
char address[50];
char phone_number[50];
char first_name[50];
char last_name[50];
};
int main(struct Student arr_student[numero])
{
int i; //Counter
char tempvalue[50]; //Temporary variable to store data in the array
char search[50]; //Search value input by user
int result = 1; //Initialized result to false
for (i = 0; i < numero; i++)
{
//Asks user for input on student information.
printf("\nEnter the information for student %d\n\n", i + 1);
printf("\nEnter first name: ");
scanf("%s", tempvalue);
printf("%s", tempvalue);
//prints value to verify if tempvalue recieved
strcpy(arr_student[i].first_name, tempvalue);
//error begins with the arr_student being underlined
printf("\nEnter last name: ");
scanf("%s", tempvalue);
strcpy(arr_student[i].last_name, tempvalue);
printf("\nEnter student id: ");
scanf("%s", tempvalue);
strcpy(arr_student[i].id, tempvalue);
printf("\nEnter student gpa: ");
scanf("%s", tempvalue);
strcpy(arr_student[i].gpa, tempvalue);
printf("\nEnter student address: ");
scanf("%s", tempvalue);
strcpy(arr_student[i].address, tempvalue);
printf("\nEnter student phone number: ");
scanf("%s", tempvalue);
strcpy(arr_student[i].phone_number, tempvalue);
}
printf("Enter the last name of the student you wish to examine data for: ");
//Asks input from the user for a name to search the data for
scanf("%s", search);
for (i = 0; i < numero; i++)
{
result = strcmp(search, arr_student[i].last_name);
}
if (result == 0) //A match is found in the array
{
printf("Here is the data on the student: %s", search);
printf("First Name\t Last Name\t ID\t GPA\t Address\t Phone Number\n");
//Prints out student information
printf("%s\t%s\t%s\t%s\t%s\t%s\n",
arr_student[i].first_name, arr_student[i].last_name, arr_student[i].id,
arr_student[i].gpa, arr_student[i].address, arr_student[i].phone_number);
}
else
{
printf("The name you have entered is not in our system, please try again");
return;
}
return 0;
}
Change the invalid main() definition from
int main(struct Student arr_student[numero])
{
to
int main(void) {
struct Student arr_student[numero] = {0};
Use width limited input.
char tempvalue[50];
// scanf("%s", tempvalue);
scanf("%49s", tempvalue);

Getting user input doesn't work correctly

I am writing a simple program in C using structs. The user needs to enter some values for the struct - a name and age. After I enter the data for the first time, the second time the program just skips one of the fields and only wants me to enter the second field of the data. I can't figure out what's wrong.
struct Person {
char name[20];
int age;
};
void main(){
struct Person pArray[10];
for (int i = 0; i < 10; i++) {
printf("Please enter a name and age:\n");
printf("Name: ");
fgets(pArray[i].name, 20, stdin);
printf("Age: ");
scanf("%d", &pArray[i].age);
}
}
As you can see, after entering Jonathan and 45 for the first time, the second time it skipped the name and wants only the age. Why is this happening?
I try not to mix formatted and unformatted input (e.g., fgets and scanf). Here is your program using only fgets for input:
#include <stdio.h>
struct Person {
char name[20];
int age;
};
int main(){
struct Person pArray[10];
char numberBuffer[20];
for (int i = 0; i < 10; i++) {
printf("Please enter a name and age:\n");
printf("Name: ");
fgets(pArray[i].name, 20, stdin);
printf("Age: ");
fgets(numberBuffer, 20, stdin);
sscanf(numberBuffer, "%d", &pArray[i].age);
}
}

error: expression must have struct or union type in c

I've been working on a code to store names and grades of students, then recall the grade when the students' names are entered.
Here is my code:
#include <stdio.h>
#define N 10
#define M 2
struct a
{
char name[50];
int grade;
};
int main()
{
int i;
int j;
struct a A[N][M];
for(i=0;i<N;i++)
{
printf("Please Enter Students' Names:/n");
scanf("%s", &A[i].name);
}
for(j=0;j<M;j++)
{
printf("Please Enter Students' Grades:/n");
scanf("%d", &A[j].grade);
}
printf("Which Student's Grades Would You Like To View?/n");
if(scanf("%s", *A[i].name))
{
printf("Their Grade Is:%d/n", *A[j].grade);
}
return 0;
}
I've been getting these errors:
hw2problem2.c(21): error: expression must have struct or union type
scanf("%s", &A[i].name);
^
hw2problem2.c(26): error: expression must have struct or union type
scanf("%d", &A[j].grade);
^
hw2problem2.c(29): error: expression must have struct or union type
if(scanf("%s", *A[i].name))
^
hw2problem2.c(31): error: expression must have struct or union type
printf("Their Grade Is:%d/n", *A[j].grade);
^
compilation aborted for hw2problem2.c (code 2)
Any help with the errors or the program in general would be appreciated.
Thanks.
You defined struct a A as a two dimensional array, and only specified
one dimension in scanf("%s", &A[i].name); and scanf("%d", &A[j].grade);.
You have a couple of other issues, like scanf("%s", &A[i].name);... where the
& is unnecessary.
Your program should be like this
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
{
printf("Please Enter Students' Grades:/n");
scanf("%d", &A[i][j].grade);
printf("Please Enter Students' Names:/n");
scanf("%s", &A[i][j].name);
}
}
Because, A[i] is of type struct a*, not struct a. It should be A[i][j]
Logically, your array should be 1-D. Hence, loop should like:
struct a A[N];
for(i=0;i<N;i++)
{
printf("Please Enter Students' Names:/n");
scanf("%s", &A[i].name);
}
for(j=0;j<N;j++)
{
printf("Please Enter Students' Grades:/n");
scanf("%d", &A[j].grade);
}
If it is subject wise, then it should be 2D and use nested loop as shown.
No need to use 2D array. Simply try this..
#include <stdio.h>
#define N 3
struct a
{
char name[50];
int grade;
};
int main()
{
int i;
struct a A[N];
char sname[50];
for(i=0;i<N;i++)
{
printf("Please Enter Students' Names:/n");
scanf("%s", A[i].name);
}
for(i=0;i<N;i++)
{
printf("Please Enter Students' Grades:/n");
scanf("%d",&A[i].grade);
}
printf("Which Student's Grades Would You Like To View?/n\n");
printf("Enter the name...\n");
scanf("%s",sname);
for(i=0;i<N;i++)
{
if(strcmp(A[i].name,sname)==0)
{
printf("%s grade is %d\n",A[i].name,A[i].grade);
break;
}
else
{
if(i==N-1)
printf("No such a name in your list...\n");
}
}
return 0;
}

Resources