I am coming back from after reading this c-faq question I am totaly confused what happening here.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main ()
{
char ar[3]="NIS", *c;
printf ("%s\n", ar);
strcpy (c, ar);
printf ("%s\n", c);
if (ar[4] == '\0')
{
printf ("Null");
}
else
{
printf ("%c\n", ar[4]);
}
}
Here I have assigned “NIS” Equal size of declare array.and when i try to access ar[3],ar[4] it giving null why ? it’s ok in case of ar[3] but why in case of ar[4] Another thought: In c-faq it was mentioned that if you assign any string equal to the size of declared array, you can’t use printf (“%s”), and strcpy() on that array as it is mentioned in c-faq. But in my above code i have used printf as well as strcpy here both working fine.It might be i have interpreted wrong please correct me. and another question is that When I try to compare ar[5] with null it is not printing anything that’s ok but why it is printing Null for ar[4].My thought on this “NIS” String will store in memory like this..
Thanks in advance.
--------------------------------------------------------
| N | I | S | /0 | Garbage value here
|_______|________|_______|________|_____________________
ar[0] ar[1] ar[2] ar[3]
Well Here ar[3] is giving null when I compare it with ‘\0’ that’s ok but when I comapre it with ar[4] still it giving me null instead of some garbage value..
Your code exhibits undefined behaviour. It works for you by chance, but on another machine it could fail. As you understood from the FAQ, the code is not valid. But that does not mean it will always fail. That is simply the nature of undefined behaviour. Literally anything can happen.
Accessing
ar[3]is illegal because that is beyond the end of the array. Valid indices for this array are 0, 1 and 2.You did not allocate memory for
cso any de-referencing of the pointer is undefined behaviour.Your
maindeclaration is wrong. You should write: