Tuesday, July 14, 2009

Accessing Elements of C Structure?

I'm taking a class in which most of the programming is done in C. I'm much more familiar with C++. Anyways, I am using structures in a program and from C++ I know you can access an element of a structure using the dot operater (i.e. structureVariable.element). However, someone in my class mentioned something about using -%26gt; instead of the dot operator. In my program in one C file I used the dot operator and it worked just fine (in the file a structure variable was declared). But in another file, where a function receives the structure variable like this OPTION *options the dot operator gives me an error, but when I switch to -%26gt; it works. I tried using the -%26gt; in the other file but it gave me errors. Why is this happening? When is it appropriate to use the dot operator and when is it appropriate to use -%26gt;?

Accessing Elements of C Structure?
Hi,


suppose u have a structure





struct struct_name


{


int age;


};





now u declare two structure variables


struct struct_name a,*p;


where a is a normal structure variable and *p is a structure pointer.





Now if u want to access structure variable age then write:





a.age; (If u r accessing structure element with a structure variable, use a period.





p-%26gt;age; (If u r accessing structure element with a structure pointer, use a -%26gt;.
Reply:It is pretty much the same in c and c++:





If you declare a type you normally refer its elements with a dot operator:





typedef struct student


{


int age;


int class;


char name[25];


}boy;





int main()


{


.


.


.


boy b1;


b1.age = 16;


printf("%d", b1.age);


...


}





If you are declaring a pointer to a type or any array of types you use the -%26gt; operator. Think it is called the indirection or the redirection operator...





boy *b1;





b1 = (boy) malloc(sizeof(boy));


b1-%26gt;age = 16;


printf("%d", b1-%26gt;age);


No comments:

Post a Comment