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

标签 c pointers structure

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

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/

相关文章:

c - realloc() 一个递增的指针

c - 如何测试移植到 64 位的代码(的指针)?

c++ - 使用函数指针填充结构数组

c++ - 重新分配指针给出错误

c++ - 创建局部结构的 std::vector 时出错

c - 新字符错误 C(新未声明)

c - valgrind - 地址是分配大小为 16 的 block 之前的 8 个字节

c - 从 RGB 到 BGRA 的快速矢量化转换

c - 使用函数指针结构的 C 包装函数

c - C 结构中未声明的标识符错误