Don't use char*
. Use std::string
, like all other here are telling you. This will eliminate all such problems.
However, for the sake of completeness and because you want to understand the background, let's analyse what is going on.
while(input != '\0'){
You probably mean:
while(*input != '\0') {
Your code compares the input
pointer itself to \0
, i.e. it checks for a null-pointer, which is due to the unfortunate automatic conversion from a \0
char
. If you tried to compare with, say, 'x'
or 'a'
, then you would get a compilation error instead of runtime crashes.
You want to dereference the pointer via *input
to get to the char
pointed to.
a += input[i];
input++;
i++;
This will also not work. You increment the input
pointer, yet with [i]
you advance even further. For example, if input
has been incremented three times, then input[3]
will be the 7th character of the original array passed into the function, not the 4th one. This eventually results in undefined behaviour when you leave the bounds of the array. Undefined behaviour can also be the "bus error 10" you mention.
Replace with:
a += *input;
input++;
i++;
(Actually, now that i
is not used any longer, you can remove it altogether.)
And let me repeat it once again: Do not use char*
. Use std::string
.
c_str()
function (e.g.,a.c_str()
), it returns aconst char*
.std::string
throughout.std::string::c_str
, beware: The returned pointer is invalidated when thestd::string
goes out of scope. So you can not use this to return the buffer of a local string.std::string a("jyillit");
where&a[0]
ischar*
with wite access you're talkin about