gpt4 book ai didi

c - 分配二维数组时出现段错误?

转载 作者:太空宇宙 更新时间:2023-11-04 07:52:48 27 4
gpt4 key购买 nike

我在第 57 行遇到段错误,我不确定为什么...:

41    int numRows = C/(K*L);
42 int numCols = K;
43
44 tagArray = (int **) malloc(numRows*sizeof(int)); // creates rows in array with C/K*L rows
45 lruArray = (int **) malloc(numRows*sizeof(int)); // creates rows in array with C/K*L rows
46
47 for(int i = 0; i<numRows;i++)
48 {
49 *(tagArray + i) = (int*) malloc(numCols*sizeof(int)); // fills each row with K columns
50 *(lruArray + i) = (int*) malloc(numCols*sizeof(int)); // fills each row with K columns
51 }
52
53 for(int i = 0; i<numRows; i++)
54 for(int j = 0; j<numCols; j++)
55 {
56 tagArray[i][j] = -1;
57 lruArray[i][j] = -1;
58 }
59

有什么我想念的吗?我非常有信心我的 mallocing 是正确的..

最佳答案

tagArray = (int **) malloc(numRows*sizeof(int)); // creates rows in array with C/K*L rows
lruArray = (int **) malloc(numRows*sizeof(int)); // creates rows in array with C/K*L rows

您必须为 int* 而不是 int 分配空间。

不要在 C 中强制转换 malloc() 的结果!

关于c - 分配二维数组时出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52692579/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com