Sunday, July 12, 2009

The follwoing C code gives a different outcome. Plz explain.?

char nm[3];


nm[0]='a';


nm[1]='b';


nm[2]='c';


printf("%d",strlen(nm));





output is 6 why?

The follwoing C code gives a different outcome. Plz explain.?
In the following code, the nm character array is defined as 3 bytes long.





char nm[3];


nm[0]='a';


nm[1]='b';


nm[2]='c';


printf("%d",strlen(nm));





If you changed the code to:








char nm[4];


nm[0]='a';


nm[1]='b';


nm[2]='c';


nm[3]='\0';


printf("%d",strlen(nm));





the output would be 3.





This is because you need to null terminate the array for the program to be reliable. Who knows what the compiler placed after the nm array in memory.
Reply:see u r storing ascii values of a , b, c. the ascii values are nothing but integers....each int is of size 2.





therefore for 3 int's its giving 6.......





try using double quotes.... and reply


char nm[3];


nm[0]="a"';


nm[1]="b";


nm[2]="c";


printf("%d",strlen(nm));


No comments:

Post a Comment