How to access the pointer of a struct within the pointer of another struct?

Asked

Viewed 313 times

1

typedef struct vertice
{  
    int num_vertice;    
    int profundidade;    
    struct vertice **vertices_adja;

} Vertice;

typedef struct grafo
{    
   int qtd_vertices;   
   int *Vertice;

} Grafo;

I want to access the attributes of struct 'Vertice' inside the graph, the way I’m trying to do it is this.

Grafo* criarGrafo(int *vertices, int qtd_vertices)
{     
   Grafo *grafo_A;

   grafo_A = malloc(sizeof(Grafo));

   grafo_A->Vertice = alocarVertices(qtd_vertices);

    if(grafo_A->Vertice != NULL)
    {
       grafo_A->qtd_vertices = qtd_vertices;

       int i = 0 ;

       for( ; i < qtd_vertices; i++)
       {
         (grafo_A)->Vertice[i]->num_vertice = vertices[i];  <-- Aqui está erro "error: invalid type argument of ‘->’ (have ‘int’)"
       }
        return grafo_A;
     }
}

2 answers

1

Vertice within the struct grafo has kind int *.
These two types are not compatible.
When you index a type value int * get a int and a type value int has no members.

Defines the struct grafo as containing a pointer to the struct vertice

typedef struct vertice
{
    int num_vertice;
    int profundidade;
    struct vertice **vertices_adja;
};

typedef struct grafo
{
   int qtd_vertices;
   struct vertice *Vertice;
};

After this you can do

    grafo_A->Vertice[i].num_vertice = vertices[i];
  • Just one more question, the struct ' Vertice' inside the graph is a pointer, so I wouldn’t have to reference it with the operator "->", so: graph_A->Vertice[i]->num_vertice; why this isn’t correct?

  • Vertice is a type pointer struct vertice *; Vertice[i] is a type object struct vertice.

1


No place where you point out how error has a small concept flaw

(grafo_A)->Vertice[i]->num_vertice = vertices[i];

(grafo_A) is a logo pointer -> is correct... You access Vertice however you used indexing, IE, Vertice[i] is an instance not a pointer so should have used a . as below

(grafo_A)->Vertice[i].num_vertice = vertices[i];

This is because every vector/matrix is a pointer...

int a[10];
cout<<*(a)<<endl; // 'a' aponta para o primeiro endereço a[0] de memoria

// a+9 é o ultimo endereço do vetor e *(a+9) é a instancia do endereço
// então, *(a+9) == a[9]
cout << a[9] << "==" << *(a+9);

That is, another possible solution would be to write as follows:

(grafo_A)->(Vertice + i)->num_vertice = vertices[i];
  • Okay, entedi, thanks for the help! Helped me a lot...

  • For nothing, mark as useful if you answered your question

Browser other questions tagged

You are not signed in. Login or sign up in order to post.