"Paminu" <ja******@asd.com> wrote in message
news:di**********@news.net.uni-c.dk...
I thought that "->" was only used with pointers. Why is it that it is also
allowed to use it on arrays??
struct test {
int a;
int b;
};
struct test array[5];
void wierd()
{
array->b = 200;
printf("array->b: %d\n", array->b);
}
int main()
{
wierd();
return 1;
}
It is not allowed if I do something like:
array[1]->b = 200;
so how do I know which element that gets field b set to 200 when I type:
array->b = 200;
hologram>cat my_array.c
#include <stdio.h>
struct test
{
int a;
int b;
}; /* struct test */
struct test array[5];
void wierd(void) /* BTW, itz spelled "weird" */
{
int i;
array->b = 200;
printf("array->b: %d\narray[0].b: %d\n\n", array->b, array[0].b);
for(i=0; i<5; i++)
{
(array+i)->a = i;
(array+i)->b = i * i;
} /* for i */
} /* wierd */
int main(void)
{
int i;
wierd();
for(i=0; i<5; i++)
{
printf("(array+%d)->a: %d; (array+%d)->b: %d\n", i, (array+i)->a, i,
(array+i)->b);
printf("array[%d].a: %d; array[%d].b: %d\n\n", i, array[i].a, i,
array[i].b);
} /* for i */
return 0;
} /* main */
hologram>gcc -Wall -ansi -pedantic -o my_array.exe my_array.c
hologram>my_array.exe
array->b: 200
array[0].b: 200
(array+0)->a: 0; (array+0)->b: 0
array[0].a: 0; array[0].b: 0
(array+1)->a: 1; (array+1)->b: 1
array[1].a: 1; array[1].b: 1
(array+2)->a: 2; (array+2)->b: 4
array[2].a: 2; array[2].b: 4
(array+3)->a: 3; (array+3)->b: 9
array[3].a: 3; array[3].b: 9
(array+4)->a: 4; (array+4)->b: 16
array[4].a: 4; array[4].b: 16
Bottom line: there are a couple of different ways of coding the same thing
due to the *similar* properties of arrays and pointers in C. However you
will probably want to refer to section 6 of the C FAQ
(
http://www.faqs.org/faqs/C-faq/faq/) to learn what the similarities (and
most important, the differences) really are.
-Charles