call by reference pointers to array of structures

Discussion in 'C' started by Sanjanna, Sep 20, 2010.

  1. Sanjanna

    Sanjanna New Member

    Joined:
    Sep 20, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hi

    I have a prob in my code which am trying to debug from past 2 days. Can i get help on this.

    i have a structure declared in header file
    Code:
    typedef struct
    {
      char a;
      int b;
      } struct2;
    
    This is declared in my current pgm where   struct2 *test is similar to struct2
    typedef struct
    {
      char a;
      int b;
      int c;
      struct2 *test;
      } struct1;
    
    int copy(struct1* stats);
    
    int main (int argc, char *argv[])
    {
            struct1 stats;
            copy(&stats);
            return 0;
    }
    
    
    int copy(struct1* stats)
    {
    	struct2* str= NULL;
    	int num = 0;
    
    	printf("In copy funct \n");
    	if (read(str, &num) != 0)
    	{
    		printf("Error reading stats.\n");
    		return -1;
    	}
    	printf("Address of str  at copy  funt %u \n", str); 
    	printf("a  %s \n",&str[0]->a);
    	printf("b  %d \n",&str[0]->b);
    
    	stats->c = num;
    	stats->test = str;
    
    	return 0;
    }
    
    prob is am not able to access the elements of structure str (&str[0]->a,&str[0]->b); Also the address of str in the copy function and hte read function are not the same. I can see the values in the read function. I dnt know if i am accessing the values in the right way in the copy funciton. Can anyone plz help me with this...


    Thanks,
    Sanjana
     
    Last edited by a moderator: Sep 20, 2010
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    Why are you using array semantics to access str? Just use str->a, not &str[0]->a.

    str->a is a char, not a string. Display it with %c not %s. %s displays a NULL-terminated array of char and will not display a single char correctly.

    str doesn't exist after copy() has terminated. If you need to use it after copy() has terminated, either create it in the heap (use malloc and free) or make it static.

    read doesn't modify str, it can't, because you don't pass the address of str in. If it writes to str, this is undefined behaviour because str is NULL. Maybe what you should do instead is
    Code:
    struct2 str;
    ...
    if (read(&str, &num)...
    
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice