I have read about segmentation faults, but fail to see why one should be caused by the following code.
#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;
}
Several issues here:
sizeof(A)returns the size in bytes, not the number of elements. Therefore you are overrunning the array. You need to divide it by the size of each element.You should change your loop to this:
EDIT : Here’s a solution that doesn’t use variable length arrays: