gpt4 book ai didi

使用指向结构体中指针的指针创建二维数组

转载 作者:行者123 更新时间:2023-11-30 20:21:07 26 4
gpt4 key购买 nike

我刚刚开始构建结构,并有兴趣实现它来创建一个邻接矩阵,以便在图相关算法实现中使用。因此,我在图中创建了一个指向指针变量的指针,以将其用作二维矩阵的基地址。但是当我尝试将内存分配给数组时,它向我显示错误:

Conversion to non-scalar type requested

有人可以帮助我吗?我将完整代码发布在以下位置:-

struct graph{
int v;
int e;
struct graph **admat;
};

void main()
{
int x,i,y,z=1,n;
struct graph *G=(struct graph **)malloc(sizeof(struct graph));
printf("\nenter number of vertices: ");
scanf("%d",&G->v);
printf("\nenter number of edges: ");
scanf("%d",&G->e);
G->admat=(struct graph **)malloc(G->v * sizeof(struct graph *));
for(i=0;i<G->v;i++)
{
G[i]=(struct graph)malloc(G->v * sizeof(int));//here is the main error
}
for(x=0;x<i;x++)
{
for(y=0;y<i;y++)
{
G[x][y]=z++;
}
}
for(x=0;x<i;x++)
{
for(y=0;y<i;y++)
{
printf(" %d ",G[x][y]);
}
printf("\n");
}
}

最佳答案

这段代码就是问题所在:

struct graph *G=(struct graph **)malloc(sizeof(struct graph));
printf("\nenter number of vertices: ");
scanf("%d",&G->v);
printf("\nenter number of edges: ");
scanf("%d",&G->e);
G->admat=(struct graph **)malloc(G->v * sizeof(struct graph *));
for(i=0;i<G->v;i++)
{
G->admat[i]=(struct graph)malloc(G->v * sizeof(int));//here is the main error
}

您应该将其更改为:

struct graph *G = malloc(sizeof(struct graph));
if (G == null)
printf("Error allocating memory");

printf("\nenter number of vertices: ");
scanf("%d",&G->v);
printf("\nenter number of edges: ");
scanf("%d",&G->e);

G->admat=malloc(G->v * sizeof(struct graph *)); // I guess you mean G->admat=malloc(sizeof(struct graph *));
if (G->admat == null)
printf("Error allocating memory");
for(i = 0; i<G->v; i++)
{
G[i] = malloc(G->v * sizeof(int));
if (G[i] == null)
printf("Error allocating memory");
}

应该被删除,因为您试图为G分配int,它是一个指向struct graph的双指针。这没有任何意义。

另请阅读this link为什么不应该强制转换 malloc 的结果。

关于使用指向结构体中指针的指针创建二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43753905/

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