Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
1.39/5 (4 votes)
See more:
C++
#include<stdio.h>
int main()
{
    char a[9]="abcefghij";
    int i=0;
    while(a[i]!='\0')
    {
        printf("%d\t",a[i]);
        i++;
    }
   }


the output is 97 98 99 100 101 102 103 104 105 106 9
Posted
Updated 8-Jan-14 9:13am
v3
Comments
joshrduncan2012 8-Jan-14 14:54pm    
Have you stepped through this to see what exactly it's doing?
[no name] 8-Jan-14 23:21pm    
The code you have provided will never give the output shown - even hypothetically. There is a typo somewhere (missing d in string?). Please check it.
What compiler are you using as many modern compilers (VS2010) will not compile this?

The problem is that you're declaring a as a 9 byte length variable with 9 characters, so there is no trailing null byte '\0' because there is no space left. That means you have a string that isn't null-terminated.

The declaration of:

char a[9]="abcdefghij";

will result in the allocation of 9 bytes in the stack (because you force it declaring the array of 9 elements) and filled with the string "abcdefhij" without a null byte. No matter how many letters you add to that string, the variable will never contain more than 9 characters, and aditional letters will be discarded (in this case no letter has been discarded, but null-byte was).

Then we have declaration of:

int i=0;

That will reserve 4 aditional bytes in the stack memory. So we have in memory the following contiguous bytes (represented in hexadecimal format, please note 0x61 is letter 'a', 0x62 letter 'b', and so on):
0x61 0x62 0x63 0x64 0x65 0x66 0x67 0x68 0x69 0x00 0x00 0x00 0x00
\_____________________a____________________/ \_________i________/
  ^
  |___ pointer of a[i] when i is equal to 0, at the first iteration.

When you iterate through that array and reach the last position of your string (number 8), while-loop will continue iterating because it isn't null-terminated, causing a buffer overflow at position 9.

So let's take a look what is the situation of the memory at the 9th iteration:
0x61 0x62 0x63 0x64 0x65 0x66 0x67 0x68 0x69 0x08 0x00 0x00 0x00
\_____________________a____________________/ \_________i________/
                                         ^
                                         |___ pointer of a[i] when i is equal to 8


That overflow will reach the next variable declared at the stack, in this case i, which is an integer (4 bytes).
i at that moment will have the value of 9.

Showing that graphical:
0x61 0x62 0x63 0x64 0x65 0x66 0x67 0x68 0x69 0x09 0x00 0x00 0x00
\_____________________a____________________/ \_________i________/
                                               ^
                                               |___ pointer of a[i] when i is equal to 9


And finally the last iteration will remain like this:

0x61 0x62 0x63 0x64 0x65 0x66 0x67 0x68 0x69 0x10 0x00 0x00 0x00
\_____________________a____________________/ \_________i________/
                                                    ^
                                                    |___ pointer of a[i] when i is 10

At that point the loop will stop because a[10] is null, although it's accesing memory that belongs to other variable (i).

C language doesn't check any array boundaries (just like Java, C#,... does throwing an exception), and overflowing that boundaries will result in access or overwriting of other memory that could be used by variables, as in this case.

That's the reason why the program is displaying the last '9' and then stops.
 
Share this answer
 
v3
Comments
[no name] 8-Jan-14 15:34pm    
Aren't C strings always terminated with NUL?
Thus having an array of char and putting a string in it "The String"
The char[] receives
'T' 'h' 'e' ' ' 'S' 't' 'r' 'i' 'n' 'g' '\0'

At least that was my understanding. Then again I have no idea why he has a 9...

Ah but you noted the array is set to '9' and he filled it. That would do it.
Atul Khanduri 8-Jan-14 16:34pm    
Hello jauma,
i have a question. I have just added two lines after while i.e.
char ch = 'z';
printf("\n%d",ch);

Now it is not showing the output of printf which is inside while loop.
It is just showing the output as:

122 , ASCII value of z.

So can you give me the reason why it's happening...???
printf ref http://www.cplusplus.com/reference/cstdio/printf/[^]

Character values have decimal ASCII values. Those are the values you are seeing.

http://www.asciitable.com/[^]

[Edit]
The last number you should see is 106. Not sure why you have a 9.

The loop is set up to run until the index 'i' reaches the end of the string (i will be 9 in this case).End of a string is identified by the null[^]value of '\0' . Since the character array is initialized with a string, it has the 9th index filled with null, thus '\0'.

[Edit]
Since the array is full when initialized and no room for the null terminator was given, the loop is stopping not because of the null read from the character array but because it sees a null value (0) with in the integer memory of i.
It first reads in the first byte of i (which is '09') and outputs that. When i is incrimented again the array will deference to '00' which is nul for char (i.e. '\0') and will then terminate the loop.
 
Share this answer
 
v4
Comments
Maciej Los 8-Jan-14 15:14pm    
If you add infromation about that line: while(a[i]!='\0'), you'll get 5 from me ;)
[no name] 8-Jan-14 15:27pm    
Added :-)
Maciej Los 8-Jan-14 15:29pm    
Upvoted!
jauma 8-Jan-14 16:28pm    
That answer is incorrect and doesn't explain why the last '9' is shown. It's caused because a stack overflow as it's explained in solution 2.
[no name] 8-Jan-14 16:39pm    
Actually my answer is correct.

Your answer explains where the 9 came from. Mine did not. That does not mean it was wrong. The OP simply asked "why is the output as such". I explained the numerical representation of the ASCII as well as the loop giving references to both. I did in fact comment on your post so the self promoting was not needed. Also wondering if you are the one that voted it as a 1. As I said. The answer is not wrong.
Everything I stated was correct and was addressing the OP.
This is because you have "%d" in your printf statement that means it will display some integer value...
Since you have a character array, so ASCII values of the characters is your output...

Refer:
ASCII Value[^]
And
Printf[^]

And why it is ended with "9", so refer this[^] link...;)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900