Thread: Passing a struct via pointer question

  1. #1
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681

    Passing a struct via pointer question

    Ok I have the following code that works. My question is this: does the () around the *b isolate the pointer part from the member part? Trying to figure out why its nessary. Thanks.

    Code:
    #include <stdio.h>
    
    struct x
    {
    	int y;
    };
    
    void test2(struct x * b)
    {
    	(*b).y = (*b).y + 1;
    }
    
    
    void test(struct x a)
    {
    	printf("%d\n", a.y);
    }
    
    
    int main (void)
    {
    	struct x z;
    
    	z.y = 5;
    
    	test(z);
    	test2(&z);
    	test(z);
    	return 0;
    }

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    (*b) is an object; accessing a member of a struct or union object is done with the . operator. The parentheses are necessary because the . operator has higher precedence than unary *.

    b is a pointer; accessing a member of a struct or union through a pointer is done with the -> operator. I believe using the dereferenced pointer is equivalent to this.
    Code:
    void test2(struct x * b)
    {
    	b->y = b->y + 1;
    }
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Ok so it seems you can do it the b->y or (*b).y way.
    Hmmmm looks like its back to testing. Thanks for the answer Dave

  4. #4
    Registered User
    Join Date
    Aug 2003
    Posts
    5
    Yeah, the only time I bother to dereference and use parenthesis around the pointer is when it's a pointer to a pointer to a struct.

    like: (*some_struct)->member;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Struct question... difference between passing to function...
    By Sparrowhawk in forum C++ Programming
    Replies: 6
    Last Post: 02-23-2009, 03:59 PM
  2. Pointer Passing Question
    By NuNn in forum C Programming
    Replies: 5
    Last Post: 02-13-2009, 08:58 AM
  3. linked list question
    By brb9412 in forum C Programming
    Replies: 16
    Last Post: 01-04-2009, 04:05 PM
  4. Replies: 16
    Last Post: 10-29-2006, 05:04 AM
  5. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM