我已经编写了代码,可以生成一个包含NODES行的矩阵,每行都有用户指定的列数(请参见下面的node_degree)。然后,我用一些值填充矩阵中的每个条目(值无关紧要)。
当我使用Geany在Fedora上构建程序时,我没有收到任何错误消息。然而,当我运行程序时,我得到:
/geany run script.sh第5:3586行分段故障(核心转储)"./ad_matrix_outside_main
注意:ad_matrix_outside_main是c文件的名称。
这是程序:
#include <stdio.h>
#include <stdlib.h>
#define NODES (10)
#define CONNECTED (5)
int main()
{
int i, j;
double **matrix;
matrix = (double **)malloc(sizeof(double *)*NODES);
int node_degree[CONNECTED]; //Example: 5 nodes are connected (have non-zero degree).
for(i=0; i<CONNECTED; i++)
{
printf("Enter degree of node %dn", i); //Index is node, value is degree.
scanf("%d", &node_degree[i]);
}
for(i=0; i<CONNECTED; i++)
{
matrix[i] = (double*)malloc( sizeof(double)* (node_degree[i] + 1) );
}
for(i=0; i<NODES; i++)
{
for(j=0; j<node_degree[i]; j++)
{
matrix[i][j] = j; //j can be the node that node i connected to.
}
matrix[i][j] = NODES;
}
for(i=0; i<NODES; i++)
{
free( matrix[i] );
}
free(matrix);
return(0);
}
是什么原因导致了错误?我觉得我的记法可能有问题。
#include <stdio.h>
#include <stdlib.h>
#define NODES (10)
#define CONNECTED (5)
int main()
{
int i, j;
double **matrix;
matrix = (double **)malloc(sizeof(double *)*NODES);
int node_degree[CONNECTED]; //Example: 5 nodes are connected (have non-zero degree).
for(i=0; i<CONNECTED; i++)
{
printf("Enter degree of node %dn", i); //Index is node, value is degree.
scanf("%d", &node_degree[i]);
}
for(i=0; i<CONNECTED; i++)
{
matrix[i] = (double*)malloc( sizeof(double)* (node_degree[i] + 1) );
//给你5英镑的malloc}
for(i=0; i<NODES; i++)
{
for(j=0; j<node_degree[i]; j++)
{
matrix[i][j] = j; //j can be the node that node i connected to.
}
matrix[i][j] = NODES;
//给你分配10分!}
for(i=0; i<NODES; i++)
{
free( matrix[i] );
}
free(matrix);
return(0);
}