How do I point to structure members?

This is a discussion on How do I point to structure members? within the C++ Programming forums, part of the General Programming Boards category; I can not tell what is wrong with my code. I am just trying to learn how to point to ...

  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    31

    Question How do I point to structure members?

    I can not tell what is wrong with my code. I am just trying to learn how to point to structure members.

    Code:
    #include <iostream>
    using namespace std;
    
    struct structure
    {
    	char c;
    	int  i;
    	int a[40];
    } str;
    
    structure *p;
    p = &str;
    
    int main()
    {
    	str.a = 89;
    	str.c = 89;
    	str.i = 10;
    
    	cout << p-> c;
    
    	system("PAUSE");
    
    	return 0;
    }

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,200
    It is not possible to do assignments of pointers outside a function. Specifically,
    Code:
        structure *p;
        p = &str;
    is invalid outside a function. If you must have it outside any function, make it an initialisation.
    Code:
        structure *p = &str;
    There is a second problem, as "str.a = 89;" inside main() is invalid. This is because str.a is an array, so it cannot be an lvalue (i.e. it is not allowed on the left hand side of an assignment). This is one of those cases where - contrary to what a lot of beginners and quite a few textbooks tell you - an array and a pointer are not equivalent.

  3. #3
    Registered User
    Join Date
    Jan 2009
    Posts
    31
    Quote Originally Posted by grumpy View Post
    It is not possible to do assignments of pointers outside a function. Specifically,
    Code:
        structure *p;
        p = &str;
    is invalid outside a function. If you must have it outside any function, make it an initialisation.
    Code:
        structure *p = &str;
    Thank you, I have never heard anything about that before.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Header files and classes
    By disruptivetech in forum C++ Programming
    Replies: 5
    Last Post: 04-21-2008, 09:02 AM
  2. Help realy needed
    By ZohebN in forum C++ Programming
    Replies: 2
    Last Post: 04-08-2008, 09:37 AM
  3. Can a pointer point to different data structure?
    By franziss in forum C Programming
    Replies: 9
    Last Post: 09-04-2005, 11:51 AM
  4. Replies: 2
    Last Post: 11-28-2003, 10:50 AM
  5. Arrays and the POINT structure
    By incognito in forum C++ Programming
    Replies: 11
    Last Post: 08-02-2002, 10:20 PM

Tags for this Thread


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