Multiplying so little on the answers given here (they are all excellent) ... I came across this more than once when I just started with C, and it is easy to do.
Quick tuning of your while fix it. Everyone else gave you why; I will suspend you of how:
#include <stdio.h> int main() { char *s = "lolololololololol"; while (*s != '\0') { printf("%c", *s); s++; } }
Note that instead of an infinite loop ( while(1) ), we do a loop check to ensure that the pointer we pull out is not the null terminator for the string, thus avoiding overruns when meeting.
If you absolutely need while(1) (for example, if it's homework and the instructor wants you to use it), use the break keyword to exit the loop. The following code smells, at least to me, but it works:
#include <stdio.h> int main() { char *s = "lolololololololol"; while (1) { if (*s == '\0') break; printf("%c", *s); s++; } }
Both produce the same console output without breaking a line at the end:
lolololololololol
John rudy
source share