In article <11************ *********@k70g2 000cwa.googlegr oups.com>,
"nick048" <ni************ *@moonsoft.itwr ote:
Hi to all
I have in my program 2 arrays DIM 2:
firstArray[5] and secondArray[5]
fisrtArray is for example 'ABCD' plus terminator '\0'.
I need to create a function in order to perform this in my program:
secondArray = createArray(fir stArray);
I have. with my poor experience, create a function like this:
char *createArray(ch ar *originalArray)
{
char *tmpArray;
// Allocation
tmpArray = new char[ADIM]; // ADIM is definied as 5
//for(int i=0; i<ADIM; i++)
tmpArray = new char[ADIM];
remove the above line, it is causing memory to leak.
// original must be the fistArray
tmpArray[0] = originalArray[2];
tmpArray[1] = originalArray[0];
tmpArray[2] = originalArray[3];
tmpArray[3] = originalArray[1];
tmpArray[4] = '\0';
return tmpArray;
}
But this function don't run and I have fron VS C++ the errors:
error C2440: '=': impossible to converte from 'char' to 'char *'
Can someone help me ? I am a newby in C++.
The above function as written compiles and does what you are asking for.
Based on your comments before the code, your main must look something
like this:
int main()
{
char firstArray[5] = "ABCD";
char secondArray[5];
secondArray = createArray( firstArray ); // error here
}
The reason you are getting an error is that secondArray is already an
array, it doesn't make sense to assign a newly created array to it.
There are two ways you can fix this:
int main()
{
char firstArray[5] = "ABCD";
char* secondArray = 0;
secondArray = createArray( firstArray ); // error here
// do whatever
delete [] secondArray;
}
A better way to fix it would be to change your function to copy an array
rather than creating one:
char* copyArray( char* orig, char* copy )
{
for ( int i = 0; i < ADIM; ++i )
copy[i] = orig[i];
return copy;
}
Then use it in main like this:
int main()
{
char firstArray[5] = "ABCD";
char secondArray[5];
copyArray( firstArray, secondArray );
}
--
To send me email, put "sheltie" in the subject.