Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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");
    }
}
Posted
Updated 2-May-17 21:47pm
Comments
CPallini 3-May-17 3:20am    
Why did you write:
struct graph *G=(struct graph **) [...]
?
Nawaz Sk 3-May-17 3:24am    
its a pointer of a pointer na?
CPallini 3-May-17 3:28am    
While G is declared as a single pointer, on the right side of the expression you have a double pointer.
Arthur V. Ratz 5-May-17 11:26am    
I completely agree with CPallini

1 solution

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.

C++
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:
C++
const int COUNT = 100; // must be a constant
struct graph G[COUNT];
//then you can access the struct
G[i][x] = 0;

Pointer to pointers is an confusing issue. You must understand that everything in C is in some memory. And the program is interpreting that memory to some values. This article is a nice Beginner's Guide to Pointers.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900