-
Pointers to structures
In my book, it says that for a structure e.g.
x.name
is equivalent to:
x->name
however, when I tried to write a program using it, only
x->name will take in the values. I want to know why.
See below:
Code:
#include <stdio.h>
#include <stdlib.h>
struct complex {
int real;
int imaginary;
}A;
void take_values(struct complex *A)
{
printf("Please enter the real part of real number, A: \n");
scanf("%d", &(A->real));
printf("Please enter the imaginary part of complex number, B: \n");
scanf("%d", &(A->imaginary));
}
int main(void)
{
char repeat;
do{
take_values(&A);
printf("\nYou have typed %d + j%d ", A.real,A.imaginary);
printf("\nDo you want to repeat? Y/N?");
scanf(" %c", &repeat);
}while((repeat=='y')||(repeat=='Y'));
return(0);
}
However if i replace &(A->real) with &A.real, the compiler would give me something like this:
"The left hand argument of '.' must be a structure, not <ptr>complex ". Why doesn't it work? Thanks.
-
The dot notation is used when A is a struct, and the -> notation is used when A is a pointer to a struct. When you did this:
>>take_values(&A);
you passed the address of A to the function, therefore, within the function A is a pointer.
However, your struct A is global, your local variable name within the take_values() function is also A. I'd suggest you 1) avoid global variables unless you can't do without, and 2) don't have local variable names the same as global ones, 'cos it's confusing.
-
Thanks!
Thanks,
Its much clearer now!