
Pointers to structures & Dereferencing
|> typedef struct {
|> int a;
|> int *p;
|> } A;
|>
|> typedef struct {
|> int s;
|> A *stptr;
|> } B;
|>
|> A *func1(int w);
|>
|> main()
|> {
|> A *Aptr;
|> B *Bptr;
|> Bptr = (B *)malloc(sizeof(B));
You need to #include <stdlib.h> to ensure malloc() is properly declared.
|> /* Defining an array of 10 pointers to struct A */
|> Bptr->stptr = (A *)malloc(10*sizeof(A *)); /* 1 */
Think about what you've declared; within B, you've declared stptr to be of
type pointer-to-A. But this isn't what you want. You want an array of
pointer-to-A, not an array of A. Rewrite B as
typedef struct {
int s;
A **stptr; /* stptr is of type pointer-to-pointer-to-A */
Quote:
} B;
and then rewrite the above statement as
Bptr->stptr = malloc(10 * sizeof (A *));
(Note that if <stdlib.h> has been properly #included, casting the return
value of malloc() is not necessary, and indeed, discouraged.)
|> I am having trouble in accessing the "stptr" array inside struct B.
|> I was under impression that I can access the elements pointer to by
|> stptr as array elements but I have compilation problems. This is what I
|> do
|>
|> Bptr->stptr[0] = func1(w);
Again, your declaration of stptr was incorrect. Originally, as a pointer-to
A, stptr[0] is of type A. Once you add the extra level of indirection,
stptr[0] is of type (A *), which is what you want.
Once you make the above changes, you can do something like
for (i = 0; i < 10; ++i) Bptr->stptr[i] = func1(i);
Regards,
--
EROS Data Center -+- Telephone: (605) 594-6829
Sioux Falls, SD 57198 G|S Fax: (605) 594-6490
My opinions given here are not necessarily those of the USGS.