PDA

Click to See Complete Forum and Search --> : illegal operation


MPrestonf12
Mar 10th, 2001, 11:18 PM
I can't figure out if it is legal to allocate space as to say:


void combinestr(char *str1[80], char *str2[80]);



I get a illegal operation from this code but I can't find a way to allocate space in a buffer for the characters.


class stringop {
public:
void combinestr(char *str1, char *str2);
};
void stringop::combinestr(char *str1, char *str2)
{
strcat(str1,str2);
cout << str1;
}

parksie
Mar 11th, 2001, 06:46 AM
Pass a pointer to the first pointer, and then reallocate it using new:

void combinestr(char **str1, char *str2) {
char *pcTemp = new char[strlen(*str1)+strlen(str2)+1];

strcpy(pcTemp, *str1);
strcpy(pcTemp+strlen(*str1), str2);
pcTemp[strlen(*str1)+strlen(str2)] = 0;

delete[] (*str1);
*str1 = pcTemp;
}

However, this MUST be used with a pointer, not an array, and it must have been allocated with new. String manipulations in C are notoriously vicious, but here's an example:

char *pcStr = "Hello";
char *pcOther = new char[strlen(pcStr)+1];
strcpy(pcOther, pcStr);
// Now prepared for use
combinestr(&pcOther, pcStr);
cout << pcOther << endl;

Easiest way to use strings is the string class from the STL -- it takes virtually no more CPU time than doing it yourself.

MPrestonf12
Mar 11th, 2001, 12:25 PM
Thanks alot parksie!