Passing an element of an array of structs in C - c

I was trying to pass one of the 20 "database" structs I made
here is my prototype for the function "add"
void add(struct database test);
I want to pass my database struct and for now i'll just call it "test"
Here is my database structure
struct database
{
char ID[6];
char Duration[3];
};
main()
{
char menu;
struct database employee[20]; // I make 20 employee variables
int a = 0; /*A counter I use to edit certain structs
ie a=2 "employee[a]" = "employee[2]" */
I then call the function like this:
add(employee[a]);
a++; /*Once it exits this I want it to go to the next employee
variable so I increment the counter */
The actual function looks like this:
void add(struct database test)
{
static int a = 0;
printf("\nPlease enter a 5 digit employee number: ");
scanf("%s", test[a].ID);
a++
}
while doing this I get the error:
Error E2094 Assignment.c 64: 'operator+' not implemented in type 'database' for arguments of type 'int' in function add(database)
It says the error is at
scanf("%s", test[a].ID);
Thanks in advance for any help, and I apolgise if I have formatted this wrong, still learning for to use stack overflow, so sorry!

This is what you need to do in order to get it right:
void add(struct database* test)
{
printf("\nPlease enter a 5 digit employee number: ");
scanf("%s",test->ID);
}
int main()
{
...
int a;
struct database employee[20];
for (a=0; a<sizeof(employee)/sizeof(*employee); a++)
add(&employee[a]); // or add(employee+a);
...
}

add(struct database test) declares a struct database as parameter. This is not an array, so you cannot index it.
So
test[a]
is invalid.
Also the int a inside add() is different from the int a defined in main(). Inside add() the latter a is hidden by the former a.
Also^2 you are passing to add() a copy of the array's element declared in main(). So any modifications done to test in side add() are lost when returning from add(). They won't be visible in the array declated in main().

Related

A global struct pointer is used, but it does not take input. In C

The input lines are marked beside.
Here,
*ptr is a global struct pointer.
In the main function, the get_data() function is called but it does not take any input rather the program terminates.
#include<stdio.h>
#include<stdlib.h>
struct detail
{
int present, absent, credit, left_weeks;
};
struct detail *ptr; // global
void get_data()
{
printf("\nYou have opted for Entering the data \n");
printf("\nEnter the number of presents - ");
scanf("%d",&ptr->present); // First input
printf("\nEnter the number of absents - ");
scanf("%d",&ptr->absent); // Second input
printf("\nEnter the subject credit - ");
scanf("%d",&ptr->credit); // Third input
printf("\nEnter the number of weeks left - ");
scanf("%d",&ptr->left_weeks); // Fourth input
}
int main()
{
get_data();
}
I have checked in visual studio code and also an online compiler.
Could anyone help.
ptr points nowhere. And there is no variable of type struct detail in this code.
You probably want this:
#include<stdio.h>
#include<stdlib.h>
struct detail
{
int present, absent, credit, left_weeks;
};
struct detail foo; // << the actual variable you forgot
struct detail *ptr = &foo; // globalptr points to foo
...
and all your scanfs are wrong, the %d specifier wants a pointer to int but you provide an int.
You want this:
scanf("%d", &ptr->present);
^you forgot this
That being said, your approach is overly complicated, you probably just want this:
scanf("%d", &foo.present);
and remove the global ptr pointer alltogether.
already answered but I want to elaborate.
struct detail *ptr;
creates a pointer whose job is to point at an instance of detail. but you have not told it which one to point at (Imagine you had several instances of details in you program). In fact you dont have any instances of detail yet.
So you have to create an instance of detail
On the stack and set ptr to point at it
int main (..){
...
struct detail d;
ptr = &d;
On the heap
int main (..){
...
struct detail *d = malloc(sizeof(struct detail));
ptr = d; // d is a pointer already here
Or static global
struct detail d;
....
int main(..){
....
ptr = &d;

Can't edit integer of a struct [duplicate]

Hi friends I am practicing structures. I have these two functions one returns the structure and I copy that to the local struct in main. My second function changes those local struct members by entering different entities.
Now I have printed result after calling each function, to my surprise I notice that printed result after both the function are same. I am unable to understand what is happening here…can you guys please explain me…thanks!
#include <stdio.h>
#include <stdlib.h>
struct student{
char name[30];
float marks;
};
struct student read_student();
void read_student_p(struct student student3);
void print_student(struct student student2);
int main()
{
struct student student1;
student1 = read_student();
print_student(student1);
read_student_p(student1);
print_student(student1);
system("pause");
return 0;
}
//This is my first function
struct student read_student()
{
struct student student2;
printf("enter student name for first function: \n");
scanf("%s",&student2.name);
printf("enter student marks for first function:\n");
scanf("%f",&student2.marks);
return student2;
}
//function to print
void print_student(struct student my_student)
{
printf("Student name in first function is : %s\n",my_student.name);
printf("Student marks in first function are: %f\n",my_student.marks);
};
//My second function
void read_student_p(struct student student3)
{
printf("enter student name for second function: \n");
scanf("%s",&student3.name);
printf("enter student marks for second function: \n");
scanf("%f",&student3.marks);
}
Do you mean to write
void read_student_p(struct student* student3)
^
{
read_student_p(&student1);
^
You need to pass a pointer to read_student_p if you want to modify the struct that you are passing. Currently it is passed by value, and the modifications are lost.
Considering the _p suffix, I expect that this was intended..
When you do this:
read_student_p(student1);
And the method looks like this:
void read_student_p(struct student student3)
{
printf("enter student name for second function: \n");
scanf("%s",&student3.name);
printf("enter student marks for second function: \n");
scanf("%f",&student3.marks);
}
Structs in C are passed by value, not by reference.
So what read_student_p does is take a copy of the struct you pass in (student1), edit the copy, and then do nothing.
One solution would be to return the changed version of the struct. Another version would be to pass a pointer to a struct, and edit the struct via pointer (so that you're editing the same copy of the struct directly).
In the second function read_student_p you were calling by value, which is to say, you defined a new struct variable tmp in the function, and copied the value of student1 to this tmp value. All the modifications that you've done were on tmp value, which wouldn't affect student1.

Why is the output of this C program 0?

In this code I am trying to pass a pointer to the structure and then use this pointer to work on the structure members, but why is the output always showing 0?
#include<stdio.h>
#include<string.h>
struct student
{
int go;
} s;
void m();
void main()
{
m(&s);
printf("%d",s.go);
}
void m(struct student *ptr)
{
ptr->go;
}
struct student
{
int go;
}s;
creates a global variable. Global variables are zero initialized unless they are initialized explicitly. That statement is equivalent to:
struct student
{
int go;
};
struct student s = {0};
Hence the value of s.go is 0. The call to m does not change the values of any variables. It has no effect on the output. The output will be 0 even if the call to m(&s) is removed.
The global variable s is initialized with all members 0.
Nothing changes the value of s.go, so the output is 0.
Your question has all sorts of errors, here they are, in no particular order:
you don't need #include <string.h> if you aren't using any "string" functions
you shouldn't use global variables (if you did, it would eliminate the need to pass the pointer to s to functions to access the struct); you should remove the global variable (i.e., make it local) and continue to pass the pointer-to-struct as you are to m() in order to be able to access it outside of main() (where you should declare it)
your signature for main() is incorrect as I pointed out in a comment to OP, and naturally you are missing the return 0; statement in main() because of this
you are missing a newline in your printf()
you aren't actually doing anything with ptr->go in m(); you aren't assigning anything to it or otherwise using it. It is printing zero because, as others have pointed out, global variables (because they are static,) are (default-)initialized
Here is an example with corrections (note you can initialize s as described by others if you wish to use it's value before you modify/set it):
#include <stdio.h>
struct student
{
int go;
};
void m();
int main(void)
{
struct student s;
m(&s);
printf("%d\n", s.go);
return 0;
}
void m(struct student *ptr)
{
ptr->go = 5;
}
When you declare your structure as global , their members are always initialize with its default value, if int than '0' and if char or string than '\0' . So you are getting Value 0.
struct student
{
int go;
} s;

How to change values of a struct passed to a function

Hi friends I am practicing structures. I have these two functions one returns the structure and I copy that to the local struct in main. My second function changes those local struct members by entering different entities.
Now I have printed result after calling each function, to my surprise I notice that printed result after both the function are same. I am unable to understand what is happening here…can you guys please explain me…thanks!
#include <stdio.h>
#include <stdlib.h>
struct student{
char name[30];
float marks;
};
struct student read_student();
void read_student_p(struct student student3);
void print_student(struct student student2);
int main()
{
struct student student1;
student1 = read_student();
print_student(student1);
read_student_p(student1);
print_student(student1);
system("pause");
return 0;
}
//This is my first function
struct student read_student()
{
struct student student2;
printf("enter student name for first function: \n");
scanf("%s",&student2.name);
printf("enter student marks for first function:\n");
scanf("%f",&student2.marks);
return student2;
}
//function to print
void print_student(struct student my_student)
{
printf("Student name in first function is : %s\n",my_student.name);
printf("Student marks in first function are: %f\n",my_student.marks);
};
//My second function
void read_student_p(struct student student3)
{
printf("enter student name for second function: \n");
scanf("%s",&student3.name);
printf("enter student marks for second function: \n");
scanf("%f",&student3.marks);
}
Do you mean to write
void read_student_p(struct student* student3)
^
{
read_student_p(&student1);
^
You need to pass a pointer to read_student_p if you want to modify the struct that you are passing. Currently it is passed by value, and the modifications are lost.
Considering the _p suffix, I expect that this was intended..
When you do this:
read_student_p(student1);
And the method looks like this:
void read_student_p(struct student student3)
{
printf("enter student name for second function: \n");
scanf("%s",&student3.name);
printf("enter student marks for second function: \n");
scanf("%f",&student3.marks);
}
Structs in C are passed by value, not by reference.
So what read_student_p does is take a copy of the struct you pass in (student1), edit the copy, and then do nothing.
One solution would be to return the changed version of the struct. Another version would be to pass a pointer to a struct, and edit the struct via pointer (so that you're editing the same copy of the struct directly).
In the second function read_student_p you were calling by value, which is to say, you defined a new struct variable tmp in the function, and copied the value of student1 to this tmp value. All the modifications that you've done were on tmp value, which wouldn't affect student1.

Passing struct to function

I'm a new C programmer and I wanted to know how I can pass a struct through to a function. I'm getting an error and can't figure out the correct syntax to do it. Here is the code for it....
Struct:
struct student{
char firstname[30];
char surname[30];
};
struct student person;
Call:
addStudent(person);
Prototype:
void addStudent(struct student);
and the actual function:
void addStudent(person)
{
return;
}
Compiler errors:
line 21: warning: dubious tag declaration: struct student
line 223: argument #1 is incompatible with prototype:
This is how to pass the struct by reference. This means that your function can access the struct outside of the function and modify its values. You do this by passing a pointer to the structure to the function.
#include <stdio.h>
/* card structure definition */
struct card
{
int face; // define pointer face
}; // end structure card
typedef struct card Card ;
/* prototype */
void passByReference(Card *c) ;
int main(void)
{
Card c ;
c.face = 1 ;
Card *cptr = &c ; // pointer to Card c
printf("The value of c before function passing = %d\n", c.face);
printf("The value of cptr before function = %d\n",cptr->face);
passByReference(cptr);
printf("The value of c after function passing = %d\n", c.face);
return 0 ; // successfully ran program
}
void passByReference(Card *c)
{
c->face = 4;
}
This is how you pass the struct by value so that your function receives a copy of the struct and cannot access the exterior structure to modify it. By exterior I mean outside the function.
#include <stdio.h>
/* global card structure definition */
struct card
{
int face ; // define pointer face
};// end structure card
typedef struct card Card ;
/* function prototypes */
void passByValue(Card c);
int main(void)
{
Card c ;
c.face = 1;
printf("c.face before passByValue() = %d\n", c.face);
passByValue(c);
printf("c.face after passByValue() = %d\n",c.face);
printf("As you can see the value of c did not change\n");
printf("\nand the Card c inside the function has been destroyed"
"\n(no longer in memory)");
}
void passByValue(Card c)
{
c.face = 5;
}
The line function implementation should be:
void addStudent(struct student person) {
}
person is not a type but a variable, you cannot use it as the type of a function parameter.
Also, make sure your struct is defined before the prototype of the function addStudent as the prototype uses it.
When passing a struct to another function, it would usually be better to do as Donnell suggested above and pass it by reference instead.
A very good reason for this is that it makes things easier if you want to make changes that will be reflected when you return to the function that created the instance of it.
Here is an example of the simplest way to do this:
#include <stdio.h>
typedef struct student {
int age;
} student;
void addStudent(student *s) {
/* Here we can use the arrow operator (->) to dereference
the pointer and access any of it's members: */
s->age = 10;
}
int main(void) {
student aStudent = {0}; /* create an instance of the student struct */
addStudent(&aStudent); /* pass a pointer to the instance */
printf("%d", aStudent.age);
return 0;
}
In this example, the argument for the addStudent() function is a pointer to an instance of a student struct - student *s. In main(), we create an instance of the student struct and then pass a reference to it to our addStudent() function using the reference operator (&).
In the addStudent() function we can make use of the arrow operator (->) to dereference the pointer, and access any of it's members (functionally equivalent to: (*s).age).
Any changes that we make in the addStudent() function will be reflected when we return to main(), because the pointer gave us a reference to where in the memory the instance of the student struct is being stored. This is illustrated by the printf(), which will output "10" in this example.
Had you not passed a reference, you would actually be working with a copy of the struct you passed in to the function, meaning that any changes would not be reflected when you return to main - unless you implemented a way of passing the new version of the struct back to main or something along those lines!
Although pointers may seem off-putting at first, once you get your head around how they work and why they are so handy they become second nature, and you wonder how you ever coped without them!
You need to specify a type on person:
void addStudent(struct student person) {
...
}
Also, you can typedef your struct to avoid having to type struct every time you use it:
typedef struct student{
...
} student_t;
void addStudent(student_t person) {
...
}
Instead of:
void addStudent(person)
{
return;
}
try this:
void addStudent(student person)
{
return;
}
Since you have already declared a structure called 'student' you don't necessarily have to specify so in the function implementation as in:
void addStudent(struct student person)
{
return;
}

Resources