how to pass array struct to function? [duplicate] - c

This question already has answers here:
How do I return an array of struct from a function?
(3 answers)
Closed 5 years ago.
i'm trying to pass an array of stract to a function, but i just gave up. i´m trying to store data inside the structure function "fun()", so i can later pull up the data in function lo(); when ever i need too.
#include<stdio.h>
#include<string.h>
struct Operador
{
char nome[32];
char telefone[15];
char idade[3];
};
struct Operador* fun( ) {// im using this function to store the data
struct Operador* pItems = malloc(3 * sizeof(struct Operador));//is it necessary to use malloc
int n;
printf(" give nome: ");
scanf("%s", pItems->nome);
printf(" give telefone: ");
scanf("%s", pItems->telefone);
printf(" give age: ");
scanf("%s", pItems->idade);
return pItems;
}
//*-*-**-*-*-*-*-*-*-*-*-*-*-*-*-*-*--*-*-*-*-*-*-*-*-
void lo(struct Operador pItems)//and this function to display the data
{
struct Operador Items = pItems;
int j;
printf("\n\n");
printf("Name is: %s \n", Items->nome);
printf("telefone is: %s \n", Items->telefone);
printf("age is: %s \n", Items->idade);
printf("\n\n");
return pItems;
}
main()
{
fun(); //here i call out the function for the user to type in information
printf("\n\n click any key to see data");
system("pause");
lo(); // and this function is supposed to display information
}

You probably want this:
#include<stdio.h>
#include<string.h>
struct Operador
{
char nome[32];
char telefone[15];
char idade[3];
};
struct Operador *fun()
{
struct Operador* pItems = malloc(sizeof(struct Operador)); // allocate space for ONE structure
printf(" give nome: ");
scanf("%s", pItems->nome);
printf(" give telefone: ");
scanf("%s", pItems->telefone);
printf(" give age: ");
scanf("%s", pItems->idade);
return pItems;
}
void lo(struct Operador *pItems)
{
printf("\n\n");
printf("Name is: %s \n", pItems->nome);
printf("telefone is: %s \n", pItems->telefone);
printf("age is: %s \n", pItems->idade);
printf("\n\n");
}
int main()
{
struct Operador *op = fun(); // op points to new structure filled in by user
lo(op); // display structure
free(op); // free structure
system("pause");
}
This code is still bad (no error checking, usage of %s format specifier without length limitation, poor choice of names, age field as a string instead of an int and probably a few more), but it works as expected.

Related

C structures displaying numbers rather than user data

Kindly help me debug this code. It is not displaying the correct data. The following program is supposed to get book details from the user, dynamically allocate memory to them and display them.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "problem5.h"
int main()
{
struct books *b;
b = (struct books*)malloc(sizeof(struct books));
int command, flag = 0;
int n=0, i;
while(flag == 0)
{
printf ("1. Add Book\n");
printf ("2. View Books\n");
printf ("3. Quit\n");
scanf("%d", &command);
if (command == 1)
{
printf ("Enter Name\n");
//scanf("%d", &(b+i)->name);
scanf(" ");
gets((b+i)->name);
printf ("Enter Author\n");
//scanf("%d", &(b+i)->author);
scanf(" ");
gets((b+i)->author);
printf ("Enter Year Published\n");
scanf("%d", &(b+i)->year_published);
n=n+1;
i=n;
} else if (command == 2)
{
for(i=0; i<n; i++)
{
printf ("%d - %d by %d\n", (b+i)->year_published, (b+i)->name, (b+i)->author);
}
} else if (command == 3)
{
flag = 1;
} else
{
printf ("Invalid choice!\n");
}
}
}
The following is problem5.h header file that has the structure books. Initially I didn't declare the variables in array since I didn't want to use much memory. But I had to due to many errors.
#define PROBLEM3_H_INCLUDED
typedef struct books{
char *name[30];
char *author[30];
int year_published;
};
#endif // PROBLEM3_H_INCLUDED
When I print I am getting random numbers instead of the data the user entered.
The overall design of your code is wrong.
This is basically what you want.
I made following changements:
using meaningful variable names
changed struct book so the structure can contain one book. Also renamed it from struct books to struct book because the structure contains only one book.
allocating memory properly
using books[numberofbooks].x instead of the less readable *(books + numberofbooks)->x
More explanations in the comments.
#include <stdio.h>
#include <stdlib.h>
struct book {
char name[30];
char author[30];
int year_published;
};
int main()
{
struct book* books = NULL; // no books at all initially so we
// initialize to NULL
// so we can simply use realloc
int numberofbooks = 0;
int programend = 0;
while (programend == 0)
{
printf("1. Add Book\n");
printf("2. View Books\n");
printf("3. Quit\n");
int command;
scanf("%d", &command);
if (command == 1)
{
getchar(); // consume Enter key (due su scanf)
// allocate memory for one more book
books = realloc(books, sizeof(struct book) * (numberofbooks + 1));
printf("Enter Name\n");
gets(books[numberofbooks].name);
printf("Enter Author\n");
gets(books[numberofbooks].author);
printf("Enter Year Published\n");
scanf("%d", &books[numberofbooks].year_published);
numberofbooks++; // increment number of books
}
else if (command == 2)
{
for (int i = 0; i < numberofbooks; i++)
{
printf("%d - %s by %s\n", books[i].year_published, books[i].name, books[i].author);
}
}
else if (command == 3)
{
programend = 1;
}
else
{
printf("Invalid choice!\n");
}
}
}
There is still room for improvement though:
error checking for realloc
error checking for interactive I/O
not using the deprecated and dangerous gets
and certainly a few other things
b = (struct books*)malloc(sizeof(struct books));
Here, you are allocating memory for only one instance of struct books , But you are accessing multiple instances of struct books.
printf ("%d - %d by %d\n", (b+i)->year_published, (b+i)->name, (b+i)->author);
For i>=1 (b+i) is not defined, because you did not allocate memory for it. You have allocated memory for only (b+0).
int n=0, i;
gets((b+i)->name);
Here, i has not been initiliazed.

C - Passing Structure Parameters to Function By Reference and Value

Could I please have an explanation of what I am doing wrong.The program is for inputting and displaying student details. It must use a structure and have 2 functions; one to capture(which is to be passed by reference) and another to display (which is to be passed by value.
Here is my code:
#include <stdio.h>
struct Students{
int ID;
char name[50];
int age;
char address[100];
char course[30];
} aStudent[5];
void capture(char *name , int *age , char *address, char *course){
int i;
for(i=0; i<5; i++){
aStudent[i].ID = i+1;
printf("\nFor Student number %d:\n",aStudent[i].ID);
printf("Enter Student Name: ");
scanf ("%s", &aStudent[i].name);
printf("Enter Student Age: ");
scanf ("%d", &aStudent[i].age);
printf("Enter Student Address: ");
scanf ("%s", &aStudent[i].address);
printf("Enter Course: ");
scanf ("%s", &aStudent[i].course);
}
}
void display(char name, int age , char address, char course){
int i;
for(i=0; i<5; i++){
printf("\nStudent %d:\n",aStudent[i].ID);
printf("Name: %s\t\tAge: %d\t\tAddress: %s\t\tCourse:
%s",aStudent[i].name, aStudent[i].age, aStudent[i].address,
aStudent[i].course);
printf("\n");
}
}
void main()
{
int option, age;
char name, address, course;
printf("\t...Welcome to the Student Data System...\n\n");
printf("\nPlease Select An Option: \n1. Input Student Data\n2. View
Student Data\n3. Exit Syatem\n\n");
scanf("%d",&option);
switch(option){
case 1:
printf("Enter Student Details:\n");
capture(name, age , address, course);
break;
case 2:
printf("\nDisplaying Information:\n");
display(name, age , address, course);
break;
case 3:
close();
break;
default:
printf("\nSorry, your option is not valid.");
}
}
I have tested a number of times and it's working, but I'm getting these error messages:
Errors are shown for every argumety I've used
Also, is there a way or a line(s) of code i can use to return to the start of the switch when I am done with one of the cases - A "Return to Main Menu"?
First of all, variables you have tried to pass (either by value or by reference) when you are calling the two functions capture() and display(), haven't used anywhere because you are dealing directly with the members of the structure Students when you are capturing or displaying the results.
And the reasons you are getting syntax errors are because the capture() is expecting the addresses of the variables (&name,&age,&address,&course) and you are passing variables (name,age,address,course) themselves. And also you are using,
scanf ("%s", &aStudent[i].name);
instead of
scanf ("%s", aStudent[i].name);
In my opinion instead of making the Structure array global, declaring it inside main function and passing the whole structure array to the capture() as a reference and passing it by value to the display() is better to your objective as you need to use both call by value and reference in your code.
I have edited your code a bit and added the return to main menu option. It works for me and I apologize if my answer is long and hard to understand because this is my first answer in stackoverflow. Thanks!
#include <stdio.h>
struct Students
{
int ID;
char name[50];
int age;
char address[100];
char course[30];
};
void capture(struct Students *aStudent)
{
int i;
for(i=0; i<2; i++)
{
aStudent[i].ID = i+1;
printf("\nFor Student number %d:\n",aStudent[i].ID);
printf("Enter Student Name: ");
scanf ("%s", aStudent[i].name);
printf("Enter Student Age: ");
scanf ("%d", &aStudent[i].age);
printf("Enter Student Address: ");
scanf ("%s", aStudent[i].address);
printf("Enter Course: ");
scanf ("%s", aStudent[i].course);
}
}
void display(struct Students aStudent[])
{
int i;
for(i=0; i<2; i++)
{
printf("\nStudent %d:\n",aStudent[i].ID);
printf("Name: %s\t\tAge: %d\t\tAddress: %s\t\tCourse: %s",aStudent[i].name, aStudent[i].age, aStudent[i].address,aStudent[i].course);
printf("\n");
}
}
void main()
{
struct Students aStudent[2];
int option;
char choice = 'Y';
printf("\t...Welcome to the Student Data System...\n\n");
while(choice == 'Y' || choice == 'y')
{
printf("\nPlease Select An Option: \n1. Input Student Data\n2. View Student Data\n3. Exit Syatem\n\n");
scanf("%d",&option);
switch(option)
{
case 1:
printf("Enter Student Details:\n");
capture(aStudent);
printf("Return to main menu? (Y/N) :");
scanf(" %c",&choice);
break;
case 2:
printf("\nDisplaying Information:\n");
display(aStudent);
printf("Return to main menu? (Y/N) :");
scanf(" %c",&choice);
break;
case 3:
close();
break;
default:
printf("\nSorry, your option is not valid.");
}
}
}
You have not initialized your string instead you have initialized a character! char name, address, course; If you have used 'char *name, *address, *course;' or char name[100], address[100], course[100]; you might have got the answer ! If you use the above case you should scan using scanf("%s",name); ! Hope I answered your question !

Trying to make a structure, won't let me input a string

I'm trying to make a structure with the three variables int age, int siblings, and char[] hometown but it's not letting me insert the hometown string when the program is run. The integers work properly but it'll just skip right over the array and leave it blank. I've tried using gets and fgets but nothing seems to be working.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
struct person{
int age;
int s;
char hometown[20];
}p;
printf("Age: ");
scanf("%d",&p.age);
printf("Siblings: ");
scanf("%d",&p.s);
printf("Hometown: \n");
fgets(p.hometown, 20, stdin);
printf("Age \t Siblings \t Hometown\n");
printf("%d \t %d \t %s\n",p.age,p.s,p.hometown);
}
The local variable might already contains garbage.
Try to memset before you use for string,
So that proper null will be terminated.
Try to acquire your input with following scan(%s, p.hometown);
For strings no need of & for collecting the string.
If you still face the issue, please let me know.
This also works for town names that contains a space and is protected against buffer overflow too.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define HOMETOWN_SIZE 20
int main(){
struct person {
int age;
int s;
char hometown[HOMETOWN_SIZE + 1]; //+ 1 for terminating null character
} p;
printf("Age: ");
scanf("%d", &p.age);
printf("Siblings: ");
scanf("%d", &p.s);
printf("Hometown: \n");
getchar(); //just for consume new line from previous scanf
fgets(p.hometown, HOMETOWN_SIZE + 1, stdin); //fgets reads n-1 characters
//don't want new line in hometown name
if (p.hometown[strlen(p.hometown) - 1] == '\n')
p.hometown[strlen(p.hometown) - 1] = '\0';
printf("Age \t Siblings \t Hometown\n");
printf("%d \t %d \t %s\n", p.age, p.s, p.hometown);
return 0;
}
Try flushing the Buffer memory before taking character array input
like this
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
struct person{
int age;
int s;
char hometown[20];
}p;
printf("Age: ");
scanf("%d",&p.age);
printf("Siblings: ");
scanf("%d",&p.s);
printf("Hometown: \n");
fflush(stdin);
fgets(p.hometown, 20, stdin);
printf("Age \t Siblings \t Hometown\n");
printf("%d \t %d \t %s\n",p.age,p.s,p.hometown);
}

How to write structure members at once in a file using fwrite() function?

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
struct student{
char *name;
char *addr;
int age;
int clas;
}*stu;
int main()
{
FILE *fp;
int choice,another;
size_t recsize;
size_t length;
struct student *stu=(struct student *)malloc(sizeof(struct student));
stu->name=(char *) malloc(sizeof(char)*20);
stu->addr=(char*)malloc(sizeof(char)*20);
recsize=sizeof(*stu);
fp=fopen("student.txt","a+");
if(fp==NULL)
{
fp=fopen("student.txt","w+");
if(fp==NULL)
{
printf("cannot open the file");
exit(1);
}
}
do
{
fseek(fp,1,SEEK_END);
printf("Please Enter student Details\n");
printf("Student Name: ");
scanf("%s",stu->name);
printf("Address: ");
scanf("%s",stu->addr);
printf("Class: ");
scanf("%s",&stu->clas);
printf("Age: ");
scanf("%s",&stu->age);
fwrite(stu,recsize,1,fp);
printf("Add another Enter 1 ?\n");
scanf("%d",&another);
}while(another==1);
fclose(fp);
free(stu);
}
I have code in C which has a structure Student. I am trying to get all structure members values from user. Memory is allocated for structure and two members *name and *addr. when I try to write those values using fwrite() function in a file Student.txt it shows random output ( ཀའ㌱䔀8䵁ཀའ㈱䔀1䵁 ) like this in a file and it is not in readable form. Please provide me the best way to write members of structure in file using fwrite() function.
You need to use %d instead of %s for ints
printf("Class: ");
scanf("%s",&stu->clas);
printf("Age: ");
scanf("%s",&stu->age);
should be
printf("Class: ");
scanf("%d",&stu->clas);
printf("Age: ");
scanf("%d",&stu->age);
And as pointed out by #David Hoelzer in comments: you're writing the value of the pointers rather than what they contain, change
struct student{
char *name;
char *addr;
to
struct student{
char name[20];
char addr[20];
and delete those lines:
stu->name=(char *) malloc(sizeof(char)*20);
stu->addr=(char*) malloc(sizeof(char)*20);

Structures and fprintf()

I was wondering if it is possible to use fprintf() with a structure, because I know you can't use a "%" for the structure.
struct blackhole_register
{
int userID;
float blackhole_Mass;
char blackhole_ID[5];
char name_First[11];
char name_Last[16];
};
int main ()
{
struct blackhole_register input;
struct blackhole_register output;
FILE *blackhole_file;
if ((blackhole_file = fopen("Holter.txt","w")) == NULL)
{
printf("File location not found, the program will now end\n");
}
else
printf("Schwarzschild Radius Application by Jonathan Holter\n\n");
printf("\nFirst Name: ");
fgets(input.name_First,11,stdin);
printf("\nLast Name: ");
fgets(input.name_Last,16,stdin);
printf("\nUser ID: ");
fgets(input.userID,4,stdin);
printf("\nBlack Hole Name/ID: ");
fgets(input.blackhole_ID,20,stdin);
printf("\nBlack Hole Mass (Solar Masses): ");
fgets(input.blackhole_Mass,3,stdin);
This is what I have so far, any help would be wonderful!!
There is no magic %serialize-my-struct flag in printf format strings. You'll need to printf each field in the struct separately. Consider writing a function int print_blackhole_register(FILE*, const blackhole_register*).

Resources