Mar 31, 2020 at 8:16pm UTC
hi can someone help me i keep getting the error
error: cannot initialize return object of type 'char MyString::*' with an lvalue of type 'char *'
the code works when i just cout the answer however when i want it to return s1 i get the error
this is the function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
char MyString:: *strcatso(char * s1,const char * s2){
char *ptr=s1;
int i=0; int j=0;
//initialized counter i
while (*(s1 + i) != '\0' ) { //loop through array while characters are not null
cout<<*(s1+i);
i++; //increment counter
}
while (*(s2+j)!='\0' ){
cout << *(s2 + j);
j++;
}
while (*(s2+j)!='\0' ){
*(s1+i)=*(s2+j);
i++;
j++;
}
*(s1+i)='\0' ;
return s1;
}
Last edited on Mar 31, 2020 at 8:16pm UTC
Mar 31, 2020 at 8:36pm UTC
The function prototype should be:
char * MyString::strcatso(char * s1,const char * s2)
But there are significant problems with this code. You are appending onto s1 in line 19, but you have no guarantee that the length of s1 is big enough to contain the concatenated string. You should use std::string rather than char*.
If you must use char*, you can get the length of the string with i = strlen(s1);
Mar 31, 2020 at 11:17pm UTC
i have to use the char and i cant use any built in function such as the strlen
Apr 1, 2020 at 12:15am UTC
> the code works when i just cout the answer
no, it doesn't
and you are not printing the answer, s1 does not have the concatenation of both strings
also, ¿what's the point of doing a member function that doesn't care about the state of its object?
Apr 1, 2020 at 2:29pm UTC
you are making it harder with the * syntax.
s1[3]
is *(s1+3)
'\0' is 0
while(s1[i]) is while(*(s1+i) != '\0')
its easier to read, and easier to type using these ideas. What you have isnt wrong (speaking of the *() syntax only) but its clunky.
Last edited on Apr 1, 2020 at 2:31pm UTC