valerij wrote:
Quote:
Please help. I have been on this problem for a week now.
I am using Windows 98SE, Microsoft Visual C++ 6.0
The following program only works when the function is not
called, BUT the function does EXACTLY what is in the
main() function. I am completely at a loss.
>
//==============code
#include <iostream.h>
#include <stdlib.h>
>
int fill_a(__int64 *list) {
int n, i;
n=8;
delete [] list;
list = new __int64 [n];
for (i=0;i<n;i++) {
list[i]=5;
}
return n;
}
>
int main() {
__int64 *list;
char buffer[20];
int n, i;
list = new __int64;
>
//n = fill_a(list);
>
n=8;
delete [] list;
You shouldn't reuse that pointer, nothing forces the compiler/platform
to release the allocation at this point.
Quote:
list = new __int64 [n];
__int64 *p_list = new __int64 [n];
Quote:
for (i=0;i<n;i++) {
list[i]=5;
}
>
for (i=0;i<n;i++) {
_i64toa(list[i], buffer, 10);
cout << buffer << endl;
}
delete [] list;
return 0;
}
//==============end of code
>
When:
>
n = fill_a(list);
As already explained, the list pointer above is copied into a local.
Quote:
>
/*n=8;
delete [] list;
list = new __int64 [n];
for (i=0;i<n;i++) {
list[i]=5;
}*/
>
An error arises:
>
================================================== ==========
Microsoft Visual C++ Debug Library
>
Program: ...ES\MICROSOFT VISUAL
STUDIO\MYPROJECTS\TEST13\DEBUG\TEST13.EXE
File: dbgdel.cpp
Line: 47
>
Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
>
For information on how your program can use assertion
failure, see the Visual C++ documentation on asserts.
>
(Press Retry to debug the application)
>
[Abort] [Retry] [Ignore]
================================================== ==========
>
Thank you,
Valerij
Instead of using primitive arrays why not use std::vector instead.
If you really must use arrays and to bypass having to use dumb
pointers:
#include <iostream>
#include <ostream>
#include <algorithm>
#include <iterator>
#include <stdexcept>
template< typename T, const std::size_t Size >
class Array
{
T array[Size];
public:
Array() { }
Array(const Array& copy)
{
std::copy( copy.array,
copy.array + Size + 1,
array );
}
T& at(std::size_t idx)
{
if(idx < 0 || idx Size)
throw std::range_error("array out of range");
return array[idx];
}
void fill(const T& t)
{
std::fill( array,
array + Size + 1,
t );
}
friend std::ostream&
operator<<(std::ostream& os, const Array& r_a)
{
std::copy( r_a.array,
r_a.array + Size - 1,
std::ostream_iterator< T >(os, ", ") );
return os << r_a.array[Size] << std::endl;
}
};
int main()
{
Array< double, 5 darray;
darray.fill( 11.1 );
std::cout << darray;
try {
// double d = darray.at(6); // throws
double d = darray.at(5);
std::cout << d << std::endl;
} catch (const std::exception& r_e)
{
std::cerr << "Error: " << r_e.what();
std::cerr << std::endl;
}
}
/*
11.1, 11.1, 11.1, 11.1, 11.1
11.1, 11.1, 11.1, 11.1, 11.1
*/