I believe "\0"
is a null-terminated 2 character C string consisting of a zero followed by a zero. Use '\0'
instead, which is just a zero. Remember: use double quotes for strings and single quotes for single characters. You cannot assign a string to a string index location, so double quotes don't work like that, but you can assign a character to a string index location.
2nd error: read the documentation on strlen()
. Create n with char n[len + 1];
, NOT char n[len-1];
, in order to make n the same length as the other string. Then, null terminate with n[len]= '\0';
, not n[len - 1]= '\0';
, since strlen doesn't count the null terminator in the string. I'm confused by your code though: what is the purpose of this n string? Lastly, you're writing outside your n array as you have it written! Since you made n have size len - 1
, you would need to null terminate at index len - 2
. len - 1
in your case is outside the array! Always null terminate inside the array at the index 1 smaller than the size of the array. When the compiler knows the side of the array, such as is the case with n, do it like this instead: n[sizeof(n) - 1] = '\0';
.
You can't use a variable to set an array length in C by the way, and in C++ it may require len to be const to instantiate an array.