Hi folks. I am currently confusing myself over why the first code doesn't work when the second code works. Would someone explain to me? The differences in codes have been bolded out.
Code:
typedef struct adjMat{
int matrix[20][20];
int vertexes;
}adjMat;
void addEdge(adjMat* adjMat, int node1, int node2){
int** matrix = adjMat -> matrix;
matrix[node1][node2] = 1;
matrix[node2][node1] = 1;
}
void showGraph(adjMat* adjMat){
int v = adjMat->vertexes;
int** mat = adjMat->matrix;
for(int i = 1; i <=v; i++){
printf("Vertex %d is connected to ... ", i);
for(int j = 1; j <= v; j++){
printf("%d, ", adjMat->matrix[i][j]);
}
}
}
int main()
{
adjMat mat;
mat.vertexes = 8;
for(int i = 1; i <= mat.vertexes; i ++){
memset(mat.matrix[i][1], 0x00, sizeof(int)*9);
}
showGraph(&mat);
return 0;
}
Code:
......
int main()
{
adjMat mat;
mat.vertexes = 8;
for(int i = 1; i <= mat.vertexes; i ++){
memset(mat.matrix[i], 0x00, sizeof(int)*9);
}
showGraph(&mat);
return 0;
}
The only difference is with the argument mat.matrix[i] vs mat.matrix[i][1] to the memset function.
Also, I realized that when I degrade the 2d array variable matrix into double pointer in the showGraph() function, and then try to access the value from that double pointer, the code does not work.
Code:
void showGraph(adjMat* adjMat){
int v = adjMat->vertexes;
int** mat = adjMat->matrix;
for(int i = 1; i <=v; i++){
printf("Vertex %d is connected to ... ", i);
for(int j = 1; j <= v; j++){
printf("%d, ", mat[i][j]);
}
}
}
Thanks for helping out!