将指针复制到指向结构中某个结构的指针C

问题描述:

有两个线程需要访问相同的全局C结构。我需要从函数的值复制到以下结构将指针复制到指向结构中某个结构的指针C

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; 
} 

当我检查正确的价值观,my_queue.queue1指向相同的地址队列2,但*(my_queue.queue1)不指向同一地址*队列2。我如何使它们相同?我需要知道两种方法。首先,我如何让它们通过指针指向相同的结构,以及如果我想制作结构的副本?

+4

你不能使用更具描述性的名字呢? –

+0

我已添加更多描述性名称。 – Haz

+0

请始终使用大写字母输入名称,使用小写字母输入功能和对象名称。使代码更加可读! – Kos

我认为你的程序不能正确编译。 sizeof(struct * queue)看起来不正确。

也许你的意思是这样:

#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); 

} 

为什么你需要对malloc的结构: (结构队列* )的malloc(的sizeof(结构队列*))

如果我需要存储一个指向我不应该有malloc的指针。这两个变量都可以指向相同的地址。

例如:

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

没有必要的malloc对于k ..