我是 C 编程新手,所以我可能在这里做了一些非常愚蠢的事情。我试图从一个 2D 数组中获取值,该数组是我从大约 70m 行的文本文件中读取的。
运行代码时,出现段错误,我已将其范围缩小到第 10 行: if (i == graph[j][0])
void convertToCSR(int source, int maxNodes, int maxEdges, int* vertices, int* edges, int** graph) {
int i;
int j;
int edge = 0;
for (i = 0; i < maxNodes; i++) {
vertices[i] = edge;
for (j = 0; j < maxEdges; j++) {
if (i == graph[j][0]) {
//Sets edges[0] to the first position
edges[edge] = graph[j][1];
printf("new edge value: %d\n", edge);
edge++;
}
}
}
vertices[maxNodes] = maxEdges;}
我已经尝试过使用较小的数据集(例如 50 字节),效果很好。通过进一步测试,我打印出了 graph[0][0] 的值,并且出现了段错误。
图表已加载数据并按如下方式分配:
int num_rows = 69000000;
graph = (int**) malloc(sizeof(int*) * num_rows);
for(i=0; i < num_rows; i++){
graph[i] = (int*) malloc(sizeof(int) * 2 );
}
我还可以在此方法之外获取 graph[0][0] 的值,但不能在内部获取。我做错了什么?我感谢任何帮助。
编辑:在我的主要方法中,我正在执行以下操作:
readInputFile(file);
int source = graph[0][0];
convertToCSR(source, maxNodes, maxEdges, nodes, edges, graph);
我有正确的变量值:源。 它在convertToCSR方法中段错误。
最佳答案
您正在使用 num_rows
来存储大于 int 容量的数字。
因此,由于溢出,实际值 int num_rows 不是 69000000。
尝试使用long unsigned int num_rows
代替。
关于c - 从动态分配的二维数组中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49844034/