...Not that I wish it did, but I want to understand why!
Hello together,
I'm new to this forum because since two weeks I am trying to learn c++. Up to now the c++ reference of this website was a huge help for me, but now I don't know whom to ask. Maybe you can help me with this problem.
My code is a simple array class with standard constructor and assignment operator:
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 26 27 28 29 30 31
|
#include <stdio.h>
#include <iostream>
class Array {
public:
// Constructors
Array() {
size = 0;
array = new double[size];
fill(0);
}
Array(int x) {
size = x;
array = new double[size];
fill(0);
}
//assignment Operator
Array& operator= (const Array & B) {
size = B.size;
std::copy(B.array, B.array+size, array);
return *this;
}
//initialize the whole array with a constant value
void fill(const double & in)
{
for(int i = 0; i < size; i++) array[i] = in;
}
double* array;
int size;
};
|
Now what I don't understand is outlined here:
1 2 3 4 5 6 7 8 9 10 11
|
int main()
{
int * ip[0];
cout << ip[1]; //may cause a segfault
Array a;
Array b(2);
a = b;
cout << endl << a(1); // may not cause a segfault?
return 1;
}
|
Can you please explain to me why this is so?
As I found in the reference, std::copy does something like this:
1 2 3 4 5 6
|
template<class InputIterator, class OutputIterator>
OutputIterator copy ( InputIterator first, InputIterator last, OutputIterator result )
{
while (first!=last) *result++ = *first++;
return result;
}
|
Does this not imply that std::copy writes something to anywhere and might cause a segmentation fault? If so, how can I solve this problem, if not so, why not?
I am completely lost and would really appreciate any help!!
Best,
wedge