gpt4 book ai didi

c - 具有多个成员的结构数组

转载 作者:太空宇宙 更新时间:2023-11-04 02:50:31 25 4
gpt4 key购买 nike

在结构“saf”中,我有数组“stack”,在结构“data”中,我有“pinx”,它是结构“data”的数组。我想让数组“stack”拥有“pinx”数组作为成员,但我不知道如何从堆栈数组访问 pinx 的成员。我给你一张图片,这样你就会明白我想做什么。

enter image description here

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

struct saf
{
int head;
void **stack;
int size;
}exp1;

struct data
{
int flag;
char name[50];
};

struct data *pinx;

void init(int n)
{

pinx = malloc(sizeof(struct data) * n);
exp1.stack = malloc(n);

}

void add()
{

strcpy(pinx[0].name,"name");
pinx[0].flag=0;
exp1.stack[0]=&pinx[0];

}

int main()
{

printf("Give size: ");
scanf("%d",&exp1.size);
init(exp1.size);
add();

return 0;
}

最佳答案

就用

void *stack;

在您的 saf 结构中。

exp1.stack = malloc(n); //is not needed

然后

exp1.stack = (void *)pinx;

和访问元素

printf("%s \n", ((struct data *)exp1.stack)[0].name);

瓦尔特

关于c - 具有多个成员的结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22624447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com