+ 4

focus on programming... what is the problem of this code?

char s[] ="this is a character array"; for( ; *s != '\0' ; ++s) cout<< *s << ' ';

12th Mar 2017, 4:43 PM
mahmood motallebi
mahmood motallebi - avatar
3 odpowiedzi
+ 1
arrays are const pointers(when we use [ ] we make const pointer), so we cannot make any changes in their address, so we can't do ++c... so we shout do sth like this: char *s ="this is a character array"; for( ; *s != '\0' ; ++s) cout<< *s << ' ';
14th Mar 2017, 12:22 PM
mahmood motallebi
mahmood motallebi - avatar
+ 1
Your variable s is a pointer. You assign its address to a part of memory that holds your string. But this string is a rvalue, which means it disappears after the execution of the code line. Therefore the memory zone is not supposed to hold your string anymore (you may see it as automatically fred from the stack by the compiler), your pointer s is dangling and using it causes undefined behavior as per the c++ standard. PS: sorry for my English.
12th Mar 2017, 11:46 PM
Arthur Van Ceulen
Arthur Van Ceulen - avatar
0
We aren't in Java Q&A Forum?
14th Mar 2017, 12:56 AM
farouk
farouk - avatar