Thread: Pointer trouble

  1. #1
    Registered User
    Join Date
    Apr 2005
    Posts
    134

    Pointer trouble

    I have following program which won't complie. Can someone help locate the problem here ?

    Code:
    #include <stdio.h>
    
    #define max 10
    struct a
    {
    	int a1;	
    };
    
    struct b
    {
    	int a_cnt;
    	struct a *strt_a[max];	
    };
    
    struct c
    {
    	struct b strt_b;
    };
    
    int main(int argc, char *argv[])
    {
    	struct c *strt_c;
    
    	strt_c = (struct c *)malloc(sizeof(struct c));
    	strt_c->strt_b.a_cnt=0;
    	strt_c->strt_b->strt_a[strt_c->strt_b.a_cnt] = (struct a *)malloc(sizeof(struct a)); /*line 26*/
    	
    	strt_c->strt_b->strt_a->a1=1234; /*line 28*/
    
    	printf("strt_c->strt_b->strt_a->a1: %d\n",strt_c->strt_b->strt_a->a1); /*line 30*/
    	
    	free(strt_c->strt_b->strt_a[strt_c->strt_b.a_cnt]);   /*line 32*/
    
    	free(strt_c);
    	return 0;
    }
    when I compile I get following error on marked lines.

    ptr10.c: In function `main':
    ptr10.c:26: invalid type argument of `->'
    ptr10.c:28: invalid type argument of `->'
    ptr10.c:30: invalid type argument of `->'
    ptr10.c:32: invalid type argument of `->'
    Thanks,

  2. #2
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    Considering the expression:
    Code:
    strt_c->strt_b->strt_a
    strt_b is not a pointer, so it doesn't make sense to use ->strt_a, it should be:
    Code:
    strt_c->strt_b.strt_a.
    Further, strt_a is an array of pointers, so you need:
    Code:
    strt_c->strt_b->strt_a[0]->a1
    (or whatever index you need)

    The following changes fix it so it compiles. The code is still ridiculous:
    Code:
    strt_c->strt_b.strt_a[strt_c->strt_b.a_cnt] = (struct a *)malloc(sizeof(struct a)); /*line 26*/
    
    strt_c->strt_b.strt_a[0]->a1=1234; /*line 28*/
    
    printf("strt_c->strt_b->strt_a->a1: %d\n",strt_c->strt_b.strt_a[0]->a1); /*line 30*/
    
    free(strt_c->strt_b.strt_a[strt_c->strt_b.a_cnt]);   /*line 32*/
    Also, don't cast the return of malloc, and make sure you #include <stdlib.h>
    Last edited by cwr; 10-24-2005 at 03:35 AM. Reason: Formatting

  3. #3
    Registered User
    Join Date
    Apr 2005
    Posts
    134
    thanks, that was it. It was difficult to see it as a part of big code. So i wrote a simple code in OP to simulate it.

    Thanks again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 04-04-2009, 03:45 AM
  2. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  3. Replies: 4
    Last Post: 06-15-2005, 08:30 PM
  4. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  5. Could somebody please help me with this C program
    By brett73 in forum C Programming
    Replies: 6
    Last Post: 11-25-2004, 02:19 AM