Thread: Pointers to structures

  1. #1
    Registered User mlsbbe's Avatar
    Join Date
    Mar 2003
    Posts
    24

    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.

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    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.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  3. #3
    Registered User mlsbbe's Avatar
    Join Date
    Mar 2003
    Posts
    24

    Thanks!

    Thanks,
    Its much clearer now!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Understanding linked lists, structures, and pointers
    By yougene in forum C Programming
    Replies: 5
    Last Post: 07-13-2011, 08:13 PM
  2. Copying pointers in structures instead of the structure data?
    By Sparrowhawk in forum C++ Programming
    Replies: 7
    Last Post: 02-23-2009, 06:04 PM
  3. returning pointers to structures
    By Giant in forum C++ Programming
    Replies: 2
    Last Post: 06-20-2005, 08:40 AM
  4. pointers to arrays of structures
    By terryrmcgowan in forum C Programming
    Replies: 1
    Last Post: 06-25-2003, 09:04 AM
  5. Help with pointers and members of structures
    By klawton in forum C Programming
    Replies: 2
    Last Post: 04-19-2002, 12:34 PM