由于试图取不在内存中的值而导致的分段错误
Segmentation fault resulting from attempt to take of value not in memory
所以我理解我的分段错误是试图访问内存中未找到的地址的结果。然而,我不确定如何修复错误,我需要传递指针,以便能够在分配函数中分配内存。
int main () {
int ****s, ****t, ****u, ****v;
int numRows, numColumns;
allocateMemory(numRows, numColumns, s, t, u, v);
}
void allocateMemory(int **** &s, int **** &t, int **** &u, int **** &v) {
s = new int***;
t = new int***;
u = new int***;
v = new int***;
****s = ****t;
****t = ****s;
****u = ****v;
****v = ****u;
*s = new int**;
*t = new int**;
*u = new int**;
*v = new int**;
***s = ***t;
***t = ***s;
***u = ***v;
***v = ***u;
**s = new int*;
**t = new int*;
**u = new int*;
**v = new int*;
**s = **t;
**t = **s;
**u = **v;
**v = **u;
**s = new int*[numRows];
for(int xCount = 0; xCount < numRows; ++xCount){
s[xCount] = new int[numColumns];
}
}
第一个问题:
void allocateMemory(int **** &s, int **** &t, int **** &u, int **** &v) {
...
s[xCount] = new int[numColumns];
这将无法编译;在这个赋值中,类型不匹配。左边是int***
,右边是int*
。我能猜到你的意思,但是——
第二个问题:
void allocateMemory(int **** &s, int **** &t, int **** &u, int **** &v) {
s = new int***;
t = new int***;
u = new int***;
v = new int***;
****s = ****t;
...
您只是从这些指针中分配内存一层深度。现在您将它们解引用到四个级别。您所遵循的指针实际上并不存在。这是未定义行为。
基础问题:你在尝试一些远远超出你对指针和数组理解的东西。必须从更简单的开始。尝试一个int
和一些指向它的指针,然后一个int[]
和一个int**
,等等。不要尝试新关卡,直到之前的关卡运行完美;
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 为什么我使用 std::copy() 收到运行时错误(分段错误)?
- 为什么我的代码包含错误分段错误(核心转储)?
- 为什么会出现此错误?- 分段错误(核心转储)
- 意外的运行时错误(分段错误)
- C++将文本文件读入数组,运行错误:分段错误
- mmap 错误:分段错误/指针无效错误
- 在我的代码中找不到错误....分段错误
- 错误:分段故障(核心转储)阵列
- 用string.h将错误分段到队列中
- c++字符串流转换错误:分段错误
- 为什么我的代码显示错误分段错误(核心转储)