pointers - Unexpected C code output -
this c code:
#include <stdio.h> int main(){ int x[] = {6,1,2,3,4,5}; int *p=0; p =&x[0]; while(*p!='\0'){ printf("%d",*p); p++; } return 0; }
when run output 612345-448304448336
what digits after minus sign , why code giving this?
the condition *p != '\0'
, same *p != 0
, never met because array doesn't contain element of value 0
, , overrun array bounds , step undefined behaviour.
instead, should control array range directly:
for (int const * p = x; p != x + sizeof(x)/sizeof(x[0]); ++p) // or "p != x + 6" { printf("%d", *p); }
Comments
Post a Comment