Can you use the arrow operator with an array of type struct. For example:
struct {
char *foo;
} fooArray[10];
fooArray[0]->foo = ...
Can you use the arrow operator with an array of type struct. For example:
struct {
char *foo;
} fooArray[10];
fooArray[0]->foo = ...
Not in your case because you are accessing a struct (not a pointer to a struct) when you use
fooArray[0]
The compiler would let you know about that problem.
No, you can't. Has to be a pointer. E.g. this is OK syntax-wise (but it will segfault unless fooArray is assigned):
int main ()
{
struct {
char *foo;
}* fooArray[10];
fooArray[0]->foo = "hallo";
}
No, you have to use fooArray[0].foo
.
fooArray
is a pointer that happens to point to the first element of an array. Using the []
is dereferencing that pointer at the given element so once applied it's no longer a pointer and the ->
operator cannot be applied since that operator does both dereferencing and accessing a struct member.
you can use array operator(for accessing data members) only on pointers, fooArray[0] is not a pointer to struct, If you want to use it you take address of it and use it like
(&fooArray[0])->foo="hello";
Or declare pointer/array of pointers to struct and allocate memory to it ..like
fooArray* a=new fooArray();
a->foo="hello";
Remember the value of fooArray
by itself is a pointer. You can dereference the pointer, add to it, ...
fooArray->foo; /* same as fooArray[0].foo */
(fooArray+3)->foo; /* same as fooArray[3].foo */
Just remember that a->b
is a shorthand for (*a).b
. Keeping this in mind should help you tackle any situation. I.e, in your case fooArray[0]->foo
means (*fooarray[0]).foo
, but fooarray[0]
isn't a pointer (it's a struct), so you can not dereference it. Hence it won't work.