English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

This code compiles and runs, but the next code . . .
int main ()
{
int** array;
int x, y;
for (int i = 0; i < 10; i++)
{
array[i] = new int[10];
}
for (int i = 0; i < 10; i++)
{
delete array[i];
}
return 0;
}
The follow code crashes, why?
int main ()
{
int x, y;
int** array;
for (int i = 0; i < 10; i++)
{
array[i] = new int[10];
}
for (int i = 0; i < 10; i++)
{
delete array[i];
}
return 0;
}

The only difference is that I swapped lines 3 and 4. Why is it that the first code will compile and execute and the second code crashes? (the crash point is in the loop)

2007-07-27 10:36:12 · 4 answers · asked by Anonymous in Computers & Internet Programming & Design

4 answers

Don't use malloc, your new statements mean your in C++.

Unfourtunately for you, it is impossible to dynamically allocate a 2D Array using just new. You'll need to use other methods to do it, the two easiest ways would be just to create a numbering scheme using bit shifts or what not to combine your 2d array into a 1d array or to just use std::vector

2007-07-27 11:19:21 · answer #1 · answered by jonathanlks 4 · 0 0

You haven't allocated any space for the array. 'array' is an uninitialized pointer to an array of pointers. It is pointing into space.

Malloc some space for it before you use it.

It worked in the second one probably because you got lucky. The results of the code are non deterministic.

You are allocating the space for the second dimension of data, but not the first dimension, the array of pointers to arrays.

2007-07-27 10:45:46 · answer #2 · answered by anotherbsdparent 5 · 0 0

Actually if you taken both simple codes to a UNIX and run them both crashes, the first one runs only by luck. Your ** array is not even initialized in the first dimension although you did new'd them in the 2nd dimension.

2007-07-27 11:24:57 · answer #3 · answered by Andy T 7 · 0 0

you are declaring it wrong!

2007-07-27 11:12:43 · answer #4 · answered by Edward L 1 · 0 0

fedest.com, questions and answers