简体   繁体   English

关于C中的字符串的困惑

[英]Confusion about strings in C

Char arrays have continuously confused me in C. 字符数组一直使我对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? 但是,由于tcp_port有100个元素,这些元素在打印时如何消失? The port is only 5 characters long and the last element is null terminated. 该端口只有5个字符长,最后一个元素为null终止。 Does printf just ignore those unintialized elements, and do those uninitialized elements contain random data? printf是否会忽略那些未初始化的元素,而那些未初始化的元素是否包含随机数据?

Yes, printf() only prints the characters up to the first \\0 character. 是的, printf()仅打印最多前\\0字符的字符。 All C string functions do this. 所有C字符串函数都可以执行此操作。 They also automatically append that \\0 character when necessary, like the scanf() function there. 它们还会在必要时自动附加\\0字符,例如那里的scanf()函数。 That's why it's called a "0-terminated string". 这就是为什么它被称为“ 0终止的字符串”的原因。

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. 请注意,分配内存时必须牢记\\0字符。 Your tcp_port string can only at most 99 characters, because the last one must be 0. 您的tcp_port字符串最多只能包含99个字符,因为最后一个必须为0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM