Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   call by reference pointers to array of structures (http://www.go4expert.com/forums/reference-pointers-array-structures-t23367/)

Sanjanna 20Sep2010 21:36

call by reference pointers to array of structures
 
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

xpi0t0s 2Oct2010 13:51

Re: call by reference pointers to array of structures
 
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)...



All times are GMT +5.5. The time now is 23:37.