+4

Weird result in a char array in c

So, i decided to see if there is a character after the specified length in an array. I was taught that there is only one more which is the null pointer but the result in the code below confused me, I got random characters in a char array, look at my code below. https://code.sololearn.com/crtrcd0SFsdU/?ref=app

2/18/2020 6:52:38 PM

Yuvraj Singh

4 Answers

New Answer

+6

The confusion is because you are trying to print the character instead of it's value... printf("the char at %d is %c\n", i, msg[i]); since your message string is "hey" it consists of 4 bytes with the final byte msg[3] being the null terminating character. Since the character null is nothing it prints nothing. If you use ... printf("the value at %d is %d\n", i, (int) msg[i]); you will see the value 0 printed for the null character. The stuff after that is just other values left over in ram that are on the heap. These may be other variables used by your program or simply random data left in memory from previous programs.

+6

First thing 'i' value is not initialized so it can have any random value. but let's assume i = 0 your array has a size of 4(chars/bytes). And you are trying to access 1000 elements so obviously you will get garbage values. When you access arrays in loops you are accessing the values stored in sequential address location. After 4 bytes your array bounds ends but address does not. And by continuing accessing the values stored in those sequential address you will print garbage value.

+4

I would think that the other values are garbage values. https://www.sololearn.com/Discuss/1654860/?ref=app https://www.sololearn.com/discuss/1894346/?ref=app

0