Note that there are some explanatory texts on larger screens.

plurals
  1. POUnable to allocate pointers in C
    text
    copied!<p>I am making a graph using <strong>Adjacency Matrix</strong>.<br /><br /> This is my header file - <strong>graph.h</strong> - <br /></p> <pre><code>typedef struct Node{ int vertex; }Node_t; typedef Node_t *Row; typedef struct graph_t{ int noOfVertices; Row *rowPointer; }graph_t, *graph_p; </code></pre> <p>This is my definition file - <strong>graph.c</strong> - <br /></p> <pre><code>graph_p createGraph(int noOfVertices){ int i, j; graph_p graph = (graph_p)malloc(sizeof(graph_t)); graph-&gt;noOfVertices = noOfVertices; graph-&gt;rowPointer = (Row *)malloc(noOfVertices * sizeof(Row)); fprintf(stdout, "\nValue of graph-&gt;rowPointer: %p\n", graph-&gt;rowPointer); for(i = 0; i &lt; noOfVertices; i++){ Row r = (Node_t *)malloc(noOfVertices * sizeof(Node_t)); fprintf(stdout, "Value of r: %p\n", r); graph-&gt;rowPointer[i] = &amp;r; fprintf(stdout, "Value of graph-&gt;rowPointer[%d]: %p\n", i, graph-&gt;rowPointer[i]); } for(i = 0; i &lt; noOfVertices; i++){ for(j = 0; j &lt; noOfVertices; j++){ Row* row = graph-&gt;rowPointer[i]; fprintf(stdout, "Value of row: %p\n", row); row[j]-&gt;vertex = 0; fprintf(stdout, "Value of row[%d]-&gt;vertex: %d\n", j, row[j]-&gt;vertex); } } return graph; } </code></pre> <p>However my <strong>OUTPUT</strong> is - <br /></p> <blockquote> <p>Value of graph->rowPointer: 003E3C50 <br /> Value of r: 003E3C70 Value of graph->rowPointer[0]: 0028FEDC <br /> Value of r: 003E3C90 <br /> Value of graph->rowPointer[1]: 0028FEDC <br /> Value of r: 003E3CB0 <br /> Value of graph->rowPointer[2]: 0028FEDC <br /> Value of r: 003E3CD0 <br /> Value of graph->rowPointer[3]: 0028FEDC <br /> Value of r: 003E3CF0 <br /> Value of graph->rowPointer[4]: 0028FEDC <br /> Value of row: 0028FEDC <br /> Value of row[0]->vertex: 0 <br /> Value of row: 0028FEDC <br /> Value of row[1]->vertex: 0 <br /> Value of row: 0028FEDC <br /> Value of row[2]->vertex: 0 <br /> Value of row: 0028FEDC <br /></p> </blockquote> <p>and after this the code goes in infinite loop. <br /></p> <p>Thus there seems to be a problem when I assign <code>graph-&gt;rowPointer[i] = &amp;r;</code>, why is this? I think that I have allocated the pointers properly. Can someone tell me what is wrong? <strong>Thanks!</strong></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload