Why can't we put a 0 character in a char pointer?
It crashes on both lines.
Code:int main() { char * buf = "hello world"; buf[5] = '\0'; buf+5 = '\0'; return 0; }
This is a discussion on put 0 in char pointer within the C Programming forums, part of the General Programming Boards category; Why can't we put a 0 character in a char pointer? It crashes on both lines. Code: int main() { ...
Why can't we put a 0 character in a char pointer?
It crashes on both lines.
Code:int main() { char * buf = "hello world"; buf[5] = '\0'; buf+5 = '\0'; return 0; }
Using Code::Blocks with MSVC++ 2010.
It's because buf is pointing to a string constant, and the OS steps in and kills the program when it attempts to modify read-only memory.
Put it in a char array for success.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
I support http://www.ukip.org/ as the first necessary step to a free Europe.
Ah yeah, of course I knew that and forgot about it.
I just thought when you pass a char array in a function you could modify it but its the same.
Thanks Salem!
Using Code::Blocks with MSVC++ 2010.