开发者

Copy pointer to a pointer to a structure within a structure in C

Have two threads that need to access same global C structure. I need to copy values from the function into the following structure

typedef struct {
    struct queue ** queue1;
} my_struct;

my_struct my_queue;

my_func(struct queue ** queue2)
{
    my_queue.queue1 = queue2;
    *(my_queue.queue1) = malloc(sizeof( struct * queue));
    *(my_queue.queue1) = *queue2;
}

When I check the values, my_queue.queue1 points correctl开发者_StackOverflow社区y to same address as queue2,but *(my_queue.queue1) does not point to same address as *queue2. How do I make them same ? I need to know two approaches. First how do I make them point to same structures via pointer and what If I wanted to make a copy of the structures ?


I think your program won't compile correctly. sizeof(struct * queue) doesn't look right.

Perhaps you mean something like this:

#include <stdio.h>
#include <stdlib.h>

struct queue { int foo;};

typedef struct {
  struct queue **queue1;
} my_struct;

my_struct my_queue;

my_func(struct queue *queue2)
{
  my_queue.queue1 = (struct queue **)malloc(sizeof(struct queue **));
  *(my_queue.queue1) = queue2;
}

int main(int argc, char **argv){
  struct queue *queue2  = (struct queue *)malloc(sizeof(struct queue *));
  queue2->foo = 3;

  printf("queue2 value is %d\n", queue2->foo);

  my_func(queue2);
  printf("queue ptrs are %ld and %ld\n",
     (long)*(my_queue.queue1), (long)queue2);
  printf("queue values are %d and %d\n",
     (*(my_queue.queue1))->foo,
     queue2->foo);

}


Why do you need to malloc for the struct: (struct queue *)malloc(sizeof(struct queue *))

If I need to store a pointer to a pointer I shouldn't have to malloc. Both variables could point to same address.

For example:

int i = 1;
int *j = &i;
int **k = &j;

No malloc needed for k..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜