-1

Char arrays have continuously confused me in C.

Here is the following code:

char tcp_port[100], udp_port[6];
tcp_port[99] = '\0'; udp_port[5] = '\0';
fscanf(fp, " tcp_port=%s", tcp_port);
fscanf(fp, " udp_port=%s", udp_port);
printf("%s\n", tcp_port); printf("%s\n", udp_port);

This works and prints out the right number. However, since tcp_port has 100 elements, how do those just disappear when printing? The port is only 5 characters long and the last element is null terminated. Does printf just ignore those unintialized elements, and do those uninitialized elements contain random data?

mrQWERTY
  • 4,039
  • 13
  • 43
  • 91

1 Answers1

4

Yes, printf() only prints the characters up to the first \0 character. All C string functions do this. They also automatically append that \0 character when necessary, like the scanf() function there. That's why it's called a "0-terminated string".

The other elements can contain anything and they will be completely ignored. In practice, they usually contain random junk, but it depends on a variety of factors.

Note that when you allocate memory you must keep that \0 character in mind. Your tcp_port string can only at most 99 characters, because the last one must be 0.

Vilx-
  • 104,512
  • 87
  • 279
  • 422