pointers - C++ Substitute function -
i'm having problems following code:
/* replace c1 c2 in s, returning s */ char *substitute(char *s, char c1, char c2) { char *r = s; if (s == 0) return 0; (; *s; ++s) if (*s == c1) *s = c2; return r; } void substitute(char c1, char c2); int main() { string s = "apples"; char a; char b; cout << "before swap of char : " << s << endl; *substitute(&a, &b); cout << "after swap of char : " << s << endl; system("pause"); }
the code above should replace occurrences of char1
in string char2
. think have function down right calling bit of issue substitute
part in main showing errors.
my question how continue on here , call function in main?
edit: i've read through answers have been given i'm still confused on i'm beginner..
edit again: i've worked out! :)
here issues see code:
substitute()
should 3 arguments,char*,char,char
, or if have later functionsubstitute(char,char)
. however, sendingchar*,char*
it, compiler doesn't know function invoke (unless have function signature not showed here). reason compile time erroryou trying modify string literal, could create run time error, if fix compile time error. note string "apples" should not modified, string literal. need copy , change it. exact behavior of modifying undefined, pointed @6502 (reference on comments)
your code poorly idented (though edit fixed issue).
a,b
not initialized , contain 'junk' values.
Comments
Post a Comment