简体   繁体   English

段错误 C++ 程序

[英]Segmentation fault C++ Program

I want to write a program to construct an*n matrix and fill it with 1 to n^2.我想写一个程序来构造一个*n 矩阵并用 1 到 n^2 填充它。 but I get a segmentation fault( core dumped).但我遇到了分段错误(核心已转储)。

I have no clue why this happens.我不知道为什么会这样。 Any help will be appreciated.任何帮助将不胜感激。

  int array[n][n];
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      array[i][j] = t;
      t++;
    }
 

I want to write a program to construct an*n matrix and fill it with 1 to n^2我想写一个程序来构造一个*n 矩阵并用 1 到 n^2 填充它

You can either use a nested standard container or write your own user-defined class modelling a matrix data structure.您可以使用嵌套的标准容器或编写您自己的用户定义的 class 建模矩阵数据结构。 Also note that there are plenty of linear algebra libraries providing well designed and tested matrix classes.另请注意,有大量线性代数库提供精心设计和测试的矩阵类。

If you decide to implement one, this may a basic starting point如果您决定实施一个,这可能是一个基本的起点

class Matrix
{
    size_t rows_, cols_;
    std::vector<int> m_;   // Note that this is ONE vector
public:
    Matrix() = default;
    Matrix(size_t r, size_t c) 
        : rows_{r}, cols_{c}, m_(r * c)
    {}
    size_t n_rows() const noexcept { 
        return rows_;
    }
    size_t n_columns() const noexcept {
        return cols_;
    }

    // I prefer to overload operator() for matrices, instead of operator[]. We need a little
    // formula to calculate the 1D index, given the 2D indices.
    auto operator() (size_t r, size_t c) const {
        return m_[r * cols_ + c];
    }
    auto& operator() (size_t r, size_t c) {
        return m_[r * cols_ + c];
    }

    auto begin() {
        return m_.begin();
    }
    auto end() {
        return m_.end();
    }
    // You may want the const version and cbegin(), cend(), too.
    // ...
};

Having that, you can complete your task in a couple of ways有了它,您可以通过几种方式完成任务

// Using a nested loop
Matrix a(n, n);
for (size_t i{}, k{}; i < a.n_rows(); ++i) {
    for (size_t j{}; j < a.n_columns(); ++j) {
        a(i, j) = ++k;
    }        
}
// Using std::iota from <numeric> header
Matrix b(n, n);
std::iota(b.begin(), b.end(), 1);

I get a segmentation fault (core dumped).我遇到分段错误(核心已转储)。 I have no clue why this happens.我不知道为什么会这样。

Those lines那些线

int n;
cin >> n;
int array[n][n];

Declare a Variable Length Array, which is not a standard compliant container.声明一个不符合标准的容器的可变长度数组。 Some compilers provide theese as an extension.一些编译器提供这些作为扩展。 In particular, gcc also has the following documentation (emphasis mine).特别是,gcc 也有以下文档(强调我的)。

6.20 Arrays of Variable Length 6.20 变长的Arrays

Variable-length automatic arrays are allowed in ISO C99 , and as an extension GCC accepts them in C90 mode and in C++ .可变长度自动arrays 允许在 ISO C99中,作为扩展 GCC 在 C90 模式和 C++ 中接受它们 These arrays are declared like any other automatic arrays, but with a length that is not a constant expression .这些 arrays 像任何其他自动arrays 一样声明,但长度不是常量表达式 The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits.存储在声明点分配,并在包含声明的块 scope 退出时释放。

Note the use of the automatic term.注意自动术语的使用。

In the comments, you say that you are testing the program with a size of 2000, which is probably too big for your environment.在评论中,您说您正在测试大小为 2000 的程序,这对您的环境来说可能太大了。 See eg why is stack memory size so limited?看看为什么堆栈 memory 大小如此有限? . .

Some problems to be solved in your code:您的代码中需要解决的一些问题:

  1. The variable length array (VLAs) are not a part of C++ standard.可变长度数组 (VLA) 不是 C++ 标准的一部分。 Thus, using syntax like:因此,使用如下语法:

     int n = 10; // non-const value int incorrect_array[n][n]; // invalid

    The array size must be known to compile time.编译时必须知道数组大小。

  2. Since the size of the array provided by you in the question is yet unclear, stack overflow may be another reason of the segfault in case you are overflowing the array size a gigantic number.由于您在问题中提供的数组大小尚不清楚,如果您将数组大小溢出一个巨大的数字,堆栈溢出可能是段错误的另一个原因。


Revised edition of the same code:相同代码的修订版:

#include <iostream>
#include <vector>

// Using this syntax just to avoid 'std::' prefix everywhere
// in this program.
using namespace std;

int main(void) {
  // Initializing multidimensional vector which will work as an array
  vector<vector<int>> multiDim;
  int size;
  int a = 1;

  cout << "The NxN size: ";
  cin >> size;

  // Providing a size of the multi-dim array
  multiDim.resize(size, vector<int>(size));

  // Initializing 1 to n^2
  for (int i{}; i < size; i++)
    for (int j{}; j < size; j++)
      multiDim[i][j] = a++;
  
  // Uncomment the next lines 5 lines to see output preview
  // for (const auto& it : multiDim) {
  //   for (const auto& subIt : it)
  //     cout << subIt << '\t';
  //   cout << endl;
  // }

  return 0;
}

The output would be: output 将是:

The NxN size: 5
1       2       3       4       5
6       7       8       9       10
11      12      13      14      15
16      17      18      19      20
21      22      23      24      25

You can ask further in the comments if you have any confusion yet.如果您有任何困惑,可以在评论中进一步询问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM