Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read values into a structure using pointers?

Tags:

c

struct

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*/
}
like image 375
Kraken Avatar asked Oct 01 '10 05:10

Kraken


People also ask

What is a structure pointer in C++?

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; }

How do you create a pointer variable in a struct?

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.

How to access members of a structure using a pointer?

There are two ways of accessing members of structure using pointer: Using indirection ( *) operator and dot (.) operator. Using arrow ( ->) operator or membership operator.

How do you dereference a pointer to a struct?

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.


2 Answers

You can write:

scanf("%d %d", &p->real, &p->imaginary);

but that depends heavily on the format in which the numbers come.

like image 141
jbernadas Avatar answered Sep 22 '22 19:09

jbernadas


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.

like image 31
Martin Törnwall Avatar answered Sep 23 '22 19:09

Martin Törnwall