C++ 段错误

标签 c++ segmentation-fault

我读过有关段错误的信息,但不明白为什么应该由以下代码引起。

#include<iostream>
#include <stdlib.h>

using namespace std;

int main(){
  int input;
  cout << "Enter length of desired array." << "\n";
  cin >> input;

  int A [input];

  //Populate and print the Array.
  for(int i=0; i<sizeof(A); i++){
    A[i] = rand()%99;
    cout << A[i] << " ";
  }
  return 0;
}

最佳答案

sizeof 以字节为单位提供大小。要查找元素计数,请将数组大小(以字节为单位)除以元素的大小:

for(int i=0; i < sizeof(A) / sizeof(A[0]); i++)

你所做的本质上是在末尾写入数组大小的 3 倍(在大多数系统上),这会导致段错误。

关于C++ 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8205244/

相关文章:

c++ - 在 C++11/C++14 中的类中存储对象类型的列表/映射

c++ - 在#define 中使用双冒号 (::)

c++ - 从 vc++ 中的 LPTSTR 获取目录名称

c++ - 将 std::unique_ptr<Derived> 转换为 std::unique_ptr<Base>

std::string 函数中的 C++ 段错误

node.js - 在 libpthread.so 中运行 Node 时出现段错误

c++ - 我如何检查该函数是否真的获得了一个定义为 const 的变量?

c++ - 段错误描述解释

C矩阵函数分割错误

c - 释放缓冲区导致无效读取