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

时间:2017-05-03 07:34:14

标签: c pointers structure

我刚刚开始构建并且有兴趣实现它来创建一个邻接矩阵,用于图形相关的算法实现。所以我在图中创建了一个指针变量指针,用它作为2D矩阵的基地址。但是,当我尝试为数组分配内存时,它显示错误:

  

转换为请求的非标量类型

任何人都可以帮助我吗?我在下面发布了整个代码: -

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

2 个答案:

答案 0 :(得分:1)

这段代码就是问题所在:

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");
}
当您尝试为int G分配struct graph时,应该删除

,这是malloc的双指针。这没有任何意义。

另请阅读this link,了解为什么不应该投射$ tesseract -v tesseract 3.04.01 leptonica-1.74.1 libjpeg 8d (libjpeg-turbo 1.3.0) : libpng 1.2.50 : libtiff 4.0.3 : zlib 1.2.8 的结果。

答案 1 :(得分:0)

假设admat包含2D矩阵数据,   这是代码。引入新变量z来存储值z。

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

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

void main()
{
    int x,i,y,z=1,n;
    struct graph *G= malloc(sizeof(struct graph));
    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 *));
    for(i=0;i<G->v;i++)
    {
        G->admat[i]=malloc(G->v * sizeof(struct graph));//here is the main error
    }
    for(x=0;x<i;x++)
    {
       for(y=0;y<i;y++)
       {
          G->admat[x][y].z=z++;
       }
    }
    for(x=0;x<i;x++)
    {
        for(y=0;y<i;y++)
        {
           printf(" %d ",G->admat[x][y].z);
        }
        printf("\n");
    }
}