I know when I have to print I use p->real
and so on but what should I write when I am reading numbers using scanf
?
#include <stdio.h>
typedef struct {
int real;
int imaginary;
} complex;
void read(complex*);
void main() {
complex c;
read(&c);
}
void read(complex* p){
/*what to write in scanf*/
}
Structure Pointer: It is defined as the pointer which points to the address of the memory block that stores a structure is known as the structure pointer. Below is an example of the same: Example: struct point { int value; }; // Driver Code int main () { struct point s; struct point *ptr = &s; return 0; }
Structures can be created and accessed using pointers. A pointer variable of a structure can be created as below: struct name { member1; member2; . . }; int main() { struct name *ptr; }. Here, the pointer variable of type struct name is created.
There are two ways of accessing members of structure using pointer: Using indirection ( *) operator and dot (.) operator. Using arrow ( ->) operator or membership operator.
You can dereference a pointer to get the address. Further, you can create a pointer to a struct. This is useful when creating abstract data types, which are structures in which you hide the details from users/other programs. To reference elements in a struct that is a pointer, use the -> notation to get to those specific values.
You can write:
scanf("%d %d", &p->real, &p->imaginary);
but that depends heavily on the format in which the numbers come.
scanf
requires you to pass the address of the memory space you want to store the result in, unlike printf
, which only requires the value (it couldn't care less where the value resides). To get the address of a variable in C, you use the & operator:
int a;
scanf("%d", &a);
Meaning: read an integer into the address I specified, in this case the address of a. The same goes for struct members, regardless of whether the struct itself resides on the stack or heap, accessed by pointer, etc:
struct some_struct* pointer = ........;
scanf("%d", &pointer->member);
And that would read an integer into the address of pointer plus the offset of member into the structure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With