Reputation: 23
In C++ I get a segmentation fault after telling the program how big the array should be (x).
Why is this happening and how do I fix this?
#include <iostream>
using namespace std;
int main()
{
int x;
cin >> x;
int array[x];
for (int *j=array; j; j++)
{
*j=0;
}
for (int *i=array; i; i++)
{
cin >> *i;
}
cout << array[3] << endl;
}
Upvotes: 0
Views: 127
Reputation: 56547
Your loop conditions are wrong.
for (int *j = array; j; j++)
and
for (int *i=array; i; i++)
will not stop at the end of the array, as the condition j
(i
) is true when traversing the array (i.e., to be false, the pointer needs to be nullptr
). In fact, pointer arithmetic past the array boundary plus one results in undefined behaviour. Your stopping condition should be
i < array + x;
Moreover, variable length arrays are an extension and not support by the C++ standard. Use new[]
instead to allocate memory, as @Joshua Byer pointed out.
Upvotes: 2
Reputation: 2254
Within a for
statement, the second expression should terminate the loop by evaluating to false
. In this case however you never terminate the loop:
for (int *j=array; j; j++)
Instead do:
for (int *j=array; j < array + x; j++)
The expression array + x
(by pointer arithmetic) means one element past the end of the array.
The above goes for both of the loops.
Upvotes: 0
Reputation: 33854
The conditions used in your loops are incorrect.
eg. for (int *j = array; j; j++)
even though j
will eventually reach the end of the array but will still never evaluate to false (allowing the loop to finish). On top of this it means you will iterate to past the end of the array and move into Undefined Behaviour, this is probably why you are seeing the segfault.
you either need to do the following (super gross solution!!!! also not C++ standard supported):
for (int i = 0, *j = array; i < x; i++, j++)
which will increment a counter and check the array at the same time as incrementing your pointer.
OR USE VECTORS
std::vector is a much easier way to do what you are doing.
int arraySize;
cin >> arraySize;
std::vector<int> array(arraySize, 0);
for (int i=0; i < arraySize; i++)
{
cin >> array[i];
}
cout << array.at(3) << endl;
Here is a live example.
Upvotes: 0
Reputation: 519
int * array;
array= new int [x];
http://www.cplusplus.com/doc/tutorial/dynamic/
Upvotes: 0