View previous topic :: View next topic |
Author |
Message |
guest Guest
|
C help please |
Posted: Sat Sep 18, 2004 5:58 pm |
|
|
Hello... could someone explain to me how to point to a variable within a struct?
ie
typedef struct
{
int x;
int y;
} my_struct
my_struct mem;
int *ptr;
(how would I piont this pointer to x or y?
ptr = &(mem.x) ??????????
thanks for any help with C |
|
|
dyeatman
Joined: 06 Sep 2003 Posts: 1934 Location: Norman, OK
|
|
|
Guest Guest
|
|
Posted: Sat Sep 18, 2004 7:33 pm |
|
|
Thanks for the reply - I've used pointers many times over etc... however I'm having trouble making a pointer to a member of a struct. I've read many references and I can't seem to figure this one out.
Since I'm a CCS customer, I thought I'd post my question here in case anybody could provide help.
Thanks. |
|
|
bdavis
Joined: 31 May 2004 Posts: 86 Location: Colorado Springs, CO
|
|
Posted: Sun Sep 19, 2004 8:59 am |
|
|
I would suggest buying the K&R book for an ANSI 'C' reference, and another book for learning 'C'. You may also want to consider using a different compiler for learning C because the CCS does not have as good of error or warning messages as a large C compiler would. You could get the Borland , or Watcom C for free I think, or a used copy of Visual C++. |
|
|
dyeatman
Joined: 06 Sep 2003 Posts: 1934 Location: Norman, OK
|
|
|
valemike Guest
|
|
Posted: Sun Sep 19, 2004 12:04 pm |
|
|
example:
struct mike_s
{
int x;
int y;
};
struct mike_s michael; // michael
struct mike_s *michael_ptr; // uninitialized pointer to mike_s
....
michael_ptr = michael; // this initialized the pointer to point to something meaningful
//now you can do stuff to the structure...
michael_ptr->x = 20;
Similiarly, you can do the following:
michael.x = 20;
So, if you work directly on the struct, you use a ".", but if you use a pointer to the structure, then you use a "->" |
|
|
guest Guest
|
|
Posted: Mon Sep 20, 2004 4:23 pm |
|
|
Again, thanks for replies.
Maybe I should explain more of what I'm trying since received answers aren't what I'm looking for ->
typedef struct{
int x;
int y;
int *ptr;
}mystruct
mystruct xyz;
void main()
{
xyz.x = 2;
xyz.y = 5;
/* now I'd like to point ptr at either x or y; */
xyz.ptr = &(xyz.x);
Is this not valid in CCS? My GCC compiler does not complain and printing out results shows that this is fine, but my CCS gives me a warning (I can't recall what that warning exactly says, since I am not at home at work at the moment). |
|
|
Mark
Joined: 07 Sep 2003 Posts: 2838 Location: Atlanta, GA
|
|
Posted: Mon Sep 20, 2004 5:37 pm |
|
|
This works just fine. No complaints except for the endless while(1)
Code: |
#include<16F876.h>
//#include<16F648A.h>
#use delay(clock=20000000)
#fuses HS,NOPROTECT,WDT,PUT,NOLVP
typedef struct
{
int x;
int y;
int *ptr;
}mystruct;
mystruct xyz;
void main()
{
xyz.x = 2;
xyz.y = 5;
/* now I'd like to point ptr at either x or y; */
xyz.ptr = &(xyz.x);
while(1)
{
}
}
|
|
|
|
|