Pointers to structures

This is a discussion on Pointers to structures within the C Programming forums, part of the General Programming Boards category; Again I am having pointer troubles. Code: #include <stdio.h> typedef struct { int a; char c; } Test; typedef Test ...

  1. #1
    Registered User
    Join Date
    Oct 2005
    Posts
    43

    Pointers to structures

    Again I am having pointer troubles.

    Code:
    #include <stdio.h>
    
    typedef struct {
    int a;
    char c; } Test;
    typedef Test *TestPtr;
    
    int main ()
    {
      Test t;
      TestPtr p;
    
      p = &t;
      *p.a = 2;
      *p.c = 'k';
      printf("%d",t.a);
      printf("%c",t.c);
    
      getchar();
      return 0;
    }
    The compiler returns the following errors:

    • request for member `a' in something not a structure or union
    • request for member `c' in something not a structure or union


    I found in a Google search a way to do this in Classic C, but not in ANSI C. Not sure I know the correct way to do this, and my book (although otherwise brilliant) doesn't either.

    Adam.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    Member access binds more tightly than dereferencing in this case, so you need to use parens:
    Code:
    (*p).a = 2;
    (*p).c = 'k';
    Or you could use the funny little arrow thingie:
    Code:
    p->a = 2;
    p->c = 'k';
    p.s. You shouldn't hide a level of indirection with a typedef, it's confusing.
    My best code is written with the delete key.

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, 05: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21