簡體   English   中英

如何將結構地址初始化為數組指針?

[英]how to initialize a struct address to array pointer?

有這個代碼:

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

struct Test { char c; } foo;

int main (void) {

   struct Test *ar[10];
   struct Test *(*p)[10] = &ar; // var 'p' is kind of type "struct Test ***p"

   *(*p+1) = malloc(sizeof(struct Test)*2); //alocated space in array p[0][1] for 2 structs

   //Now I would like to have 'foo' from above in p[0][1][1]

   // I cannot do "p[0][1][1] = foo", that is shallow copy
   // which means "p[0][1][1].c = 'c'" will have no effect
   // I need actually assign address to "&foo" to that pointer 'p'
   // something like "(*(*p+1)+1) = &foo", but that is error:
   //err: lvalue required as left operand of assignment

   // reason:
   p[0][1][1].c = 'c';
   printf("%c\n", foo.c) // no output because foo is not in the array (its address was not assign to the pointer 'p')

   return 0;
}

我想分配foo的指針struct Test ***p值。 這樣我就可以使用該指針進行操作(在該結構的成員中聲明值)。 如何做到這一點?

調用malloc后, ar[1] (以及擴展名p[0][1] )指向struct Test的 2 個實例的數組。 所以ar[1][0]ar[1][1]都是結構實例。

似乎您想要的是讓它們成為指針,以便它們可以指向foo 所以你需要一個額外的間接級別:

struct Test **ar[10];
struct Test **(*p)[10] = &ar;

// allocate space at p[0][1] for 2 struct pointers
*(*p+1) = malloc(sizeof(struct Test *)*2); 

p[0][1][1] = &foo;
p[0][1][1]->c = 'c';
printf("%c\n", foo.c);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM