C Board  

Go Back   C Board > General Programming Boards > C++ Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 03-07-2009, 07:13 PM   #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;
}
RaisinToe is offline   Reply With Quote
Old 03-07-2009, 07:39 PM   #2
Registered User
 
Join Date: Jun 2005
Posts: 1,343
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.
grumpy is offline   Reply With Quote
Old 03-07-2009, 11:34 PM   #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.
RaisinToe is offline   Reply With Quote
Reply

Tags
members, point, struct, structure

Thread Tools
Display Modes

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Header files and classes disruptivetech C++ Programming 5 04-21-2008 09:02 AM
Help realy needed ZohebN C++ Programming 2 04-08-2008 09:37 AM
Can a pointer point to different data structure? franziss C Programming 9 09-04-2005 11:51 AM
nightmare - understanding whats going on in a linked list fate C Programming 2 11-28-2003 11:50 AM
Arrays and the POINT structure incognito C++ Programming 11 08-02-2002 10:20 PM


All times are GMT -6. The time now is 04:12 AM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.0 RC2

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