Does a char array need to be one byte bigger than you intend to use? - C -


i've started learning c , bit confused when comes arrays.

#include <stdio.h>  int main() {     int i;     char j[5];      (i = 0; < 5; i++)     {         j[i] = 'a';     }      printf("%s\n", j); } 

running code prints out

aaaaa♣ 

i've read char array needs 1 byte longer string compiler can place \0 @ end. if replace code this:

#include <stdio.h>  int main() {     int i;     char j[5];      (i = 0; < 4; i++)     {         j[i] = 'a';     }      printf("%s\n", j); } 

the output is:

aaaaa 

the char array 1 byte longer i'm using. suspect why don't see odd character @ end of string?

i tried test theory following code:

#include <stdio.h>  int main() {     int i;     char j[5];      (i = 0; < 4; i++)     {         j[i] = 'a';     }      (i = 0; < 4; i++)     {        printf("%d\n", j[i]);     } } 

but, in output, see no nullbyte. because added when outputed string?

97 97 97 97 

it's job add null byte. compiler won't you. local variables left uninitialized @ runtime.

int i; char j[5];    /* 5 uninitialized characters, */  (i = 0; < 4; i++) {     j[i] = 'a'; }  j[4] = '\0';  /* explicitly add null terminator */ 

notice if use string initializer rather manually setting each character compiler handle adding null terminator you:

char j[5] = "aaaa";  /* initialize {'a', 'a', 'a', 'a', '\0'} */ 

Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -