tags:

views:

61

answers:

2

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*/
}
+4  A: 

You can write:

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

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

jbernadas
Chris Cooper
+3  A: 

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.

Martin Törnwall