使用结构创建2d数组 [英] Create 2d array using structure

查看:96
本文介绍了使用结构创建2d数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我刚刚开始结构,并有兴趣实现它来创建一个邻接矩阵,用于图形相关的算法实现,所以我创建一个指向图形中指针变量的指针,用它作为2d矩阵的基地址,但是当试图为数组分配内存显示错误:请求转换为非标量类型可以帮助我吗?我发布以下全部代码: -



我尝试过:



so i just started structure and was interested to implement it to create a adjacency matrix to use in graph related algo implementation so i create a pointer to pointer variable in the graph to use it as the base address for the 2d matrix but when tried to assign memory to the array is showing me error: conversion to non-scalar type requested can anyone help me? i am posting the whole code in the following:-

What I have tried:

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

推荐答案

通过分配G来解决问题.G是你的指针数组,所以你需要数组的数量。它是指向指针数组的指针。这个教程带来了一些见解。你的G是 ptr数组



Your problem starts earlier by allocating G. G is your pointer array so you need the count of arrays. It is a pointer to an array of pointers. This tutorial brings some insight. Your G is that array of ptr.

struct graph *G=(struct graph **)malloc(sizeof(struct *graph) * count);
G[i]=(struct graph)malloc(sizeof(struct graph));//allocate a struct



另一种可能的解决方案,当你有一个固定大小的结构:


Another possible solution, when you have a fixed size of structs:

const int COUNT = 100; // must be a constant
struct graph G[COUNT];
//then you can access the struct
G[i][x] = 0;



指向指针是一个令人困惑的问题。你必须明白C中的所有东西都在某些记忆中。程序正在将内存解释为某些值。这篇文章是一个很好的指针初学者指南


这篇关于使用结构创建2d数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆