Problem using new

J

Jochen Luig

Hi!

I think I don't grasp the concept of "new". I tried to create a
2-dimensional array using new (see code below). What I don't understand
is, why does the program below work while the lines I commented out and
labelled as "case 1" and "case 2" yield either a segmentation fault
(case 1) or a type conflict (case 2).

Thanks in advance

Jochen

Quelltext:

#include <list>

class SomeClass {
std::list<int> *list_array[10][10]; // case 2
// std::list<int> list_array[10][10]; // case 1
public:
SomeClass() {
int i,j;
for (i=0;i<=10;i++) {
for (j=0;j<=10;j++) {
list_array[j] = new std::list<int>;
// list_array[j] = *(new std::list<int>); // case 1
}
}
//list_array = new std::list<int>[10][10]; // case 2
}
};

main() {
SomeClass *x = new SomeClass();
}
 
B

ben

list<int>** list_array;

for (int i = 0; i < 10; ++i)
{
list_array = new (list*)[10]; // you forgot to new each list<int>[]

for (int j = 0; j < 10; j++)
{
list_array[j] = new list<int>;
}
}

ben
 
K

Karl Heinz Buchegger

Jochen said:
Hi!

I think I don't grasp the concept of "new". I tried to create a
2-dimensional array using new (see code below). What I don't understand
is, why does the program below work while the lines I commented out and
labelled as "case 1" and "case 2" yield either a segmentation fault
(case 1) or a type conflict (case 2).

Thanks in advance

Jochen

Part of your problems stem from the fact that you have an array overflow.
if you declare an array
int a[10]

then this array consists of 10 entries (you specify the number of entries
to the array when declaring it).

Valid indices to that array are
0, 1, 2, 3, 4, 5, 6, 7, 8, 9

(cout them, they are 10)
So the highest possible index into an array is always 1 less then the
number of elements you specified.

Now look at the following:
for (i=0;i<=10;i++) {
for (j=0;j<=10;j++) {

What values will i or j take

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

count them. They are 11! But you specified only 10 for the array sizes.

Thus the segmentation fault occours due to overflowing the array.

As for your second question:
Why do you have a type conflict.

You specified
std::list<int> *list_array[10][10];

That makes list_array a 10*10 array of pointers to list<int>
Note: This is an array of pointers. Not a pointer to an array!

Now it should be clear why

list_array = new std::list<int>[10][10];

gives a type conflict.
On the left side of the assignement there is an array, while on
the right side there is a pointer.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,668
Latest member
SamiraShac

Latest Threads

Top