Re: question for returning an array
Din?ay Ak??ren <dincay@gmail.com> wrote in message...
Following function
Are you comeing from a 'C' background?
void mdelr(int *ar1, int a, int b, int d ){
int i,j,tmp;
int *temp;
Why are those there, and un-initialized?
You don't use 'i' or 'j' outside the loops, so, let's rewrite that to be
more C++ like...
int* mdelr( int *ar1, int a, int b, int d ){
for( int i(0); i < a; ++i ){
for( int j(0); j < b; ++j ){
if( i >= d ) ar1[i*b+j] = ar1[(i+1)*b+j];
if( i == b-1 ) ar1[i*b+j] = 0;
} // for(j)
} // for(i)
int *temp( new int[(a-1)*b] );
for( int i(0); i < b*a-b; ++i )
temp[i] = ar1[i];
using std::cout;
cout << "\nlast version of array" << d << " " << ar1[0] << "\n";
delete [] ar1;
ar1 = temp;
delete [] temp;
for( int i(0); i < a-1; ++i){
for( int j(0); j < b; ++j){
cout << ar1[i*b +j] << " ";
}
cout << "\n";
}
return ar1;
} // mdelr(int*,int,int,int)
and following main block
// > int main(void)
int main(){ // C++
using std::cout;
// > int *ar1,*ar2;
// > int i,j,k;
// > int temp, sayi,ROW,COL;
// > int *pt;
Why are those there, and un-initialized?
// > ROW=COL=5;
Reserve all-caps for macros.
size_t Row(5), Col(5);
// > ar1 = new int[ROW*COL];
int *ar1( new int[ Row * Col ] );
cout << "row number to be deleted";
int sayi(0);
cin >> sayi;
// > pt = new int[sayi];
int *pt( new int[ sayi ] );
int temp(0);
// > for(i=0; i<sayi; i++){
for( int i(0); i < sayi; ++i){
cout << "Enter col num" << i;
cin >> temp;
How do you know input succeeded?
temp--;
pt[i] = temp-i;
}
You fix the rest...
// in for(k)
// > mdelr(ar1,ROW-k,COL,pt[k]);
ar1 = mdelr( ar1, Row-k, Col, pt[k] );
// > delete ar1;
// > delete pt;
delete [] ar1;
delete [] pt;
system("pause");
return 0;
} // main()
My question is why the first element of the array becomes stupid
despite all of my effords? I believe returning to main changes the
first element but I cannot prevent this.
What Erik and Alf said.
To get you going, I'll give you a short example using std::vector.
// ------------
#include <iostream>
#include <vector>
void FillVector( std::vector< int > &vec){ // non-const here
vec.push_back( 1 );
vec.push_back( 2 );
vec.push_back( 3 );
// vec.at(0) = 42; // change 1 to 42 in first element.
return;
} // FillVector(vector<int>&)
void PrintVector( std::vector< int > const &vec, // const here
std::ostream &out ){
for( std::size_t i(0); i < vec.size(); ++i ){
out<<vec.at(i)<<std::endl;
// or: out<<vec[ i ]<<std::endl;
}
// I won't show the std::copy method here.
// Look it up, or review this NG for it.
return;
} // PrintVector(vector<int>const&,ostream&)
int main(){
std::vector< int > MyVec;
FillVector( MyVec );
PrintVector( MyVec, std::cout );
return 0;
} // main()
// ------------
You can initialize the vector:
// std::vector< int > MyVec( 25 );
std::vector< int > MyVec( 25, 7 );
.....will give you a vector with 25 elements, all set to '7'.
Read-up on std::vector for much more.
--
Bob R
POVrookie