简体   繁体   中英

Why can I loop through a char array until NULL terminator when I didn't end the string with one?

Why is it possible to loop through this string until a NULL terminator if I did not end the string with one or give it an extra element to be automatically terminated with one?

char buf[5];
buf[0] = 'H';
buf[1] = 'e';
buf[2] = 'l';
buf[3] = 'l';
buf[4] = 'o';

char *p = buf;

for (p = buf; *p != '\0'; p++)
   ch_printf(ch, "%c\n", *p);

I am a newbie to C, attempting to teach myself, so please forgive my stupidity :)

Thank you for your help.

这是因为您尝试访问未分配的内存,因此buf [5]的结果为null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM