由于试图取不在内存中的值而导致的分段错误

Segmentation fault resulting from attempt to take of value not in memory

本文关键字:错误 分段 于试图 内存      更新时间:2023-10-16

所以我理解我的分段错误是试图访问内存中未找到的地址的结果。然而,我不确定如何修复错误,我需要传递指针,以便能够在分配函数中分配内存。

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**,等等。不要尝试新关卡,直到之前的关卡运行完美;

在此过程中,您将看到将其中一些结构封装在结构体中的价值。