简体   繁体   English

c的printf函数如何知道在没有\\ 0的情况下如何停止?

[英]How does c's printf function know how to stop without a \0?

I was just wondering if you could clear something up for me. 我只是想知道您是否可以为我解决一些问题。

Let's have some example code to explain my question: 让我们用一些示例代码来解释我的问题:

#include <stdio.h>

int main(void)
{
    char test[100];
    printf("%s",test);
    return 0;
}

If I am not totally mistaken, this should output randomly either some character that was at this memory address before I declared it or nothing if it was empty like in a virtual environment. 如果我没有完全误解,那么它应该随机输出在我声明它之前在此内存地址处的某个字符,或者在虚拟环境中为空时则不输出任何字符。 So, this is my understanding. 所以,这是我的理解。 The memory held before I put something in is understood as a char and written to the terminal. 在我放入东西之前保存的内存被理解为字符并写入终端。 For instance ascii 'a' = 97 = 01100001. That's why it outputs 'a'. 例如ascii'a'= 97 =01100001。这就是为什么它输出'a'的原因。 Could have been anything else. 可能还有其他事情。 Or nothing. 或者什么都没有。 And then it stops. 然后停止。

But if I put 'a' in the first position and then print it like this: 但是,如果我将“ a”放在第一个位置,然后像这样打印它:

test[0] = 'a'
printf("%s",test);

It will output 'a' and additionally to that some character or nothing and then stop. 它将输出“ a”,并另外输出该字符或不输出任何字符,然后停止。

This is how I understand arrays: An array is a pointer to the first address and the brackets are a dereferences of the address after adding the number times sizeof(type) to it. 这就是我对数组的理解:数组是指向第一个地址的指针,方括号是对地址加数字乘以sizeof(type)后的解引用。

So, in that case, the random 01100001 (Ascii 'a') found in the memory in the first example should be indistinguishable for printf from the deliberately placed 01100001 (Ascii 'a') in the second example. 因此,在那种情况下,对于第一个示例中故意放置的01100001(Ascii'a'),在第一个示例中的内存中发现的随机01100001(Ascii'a')与第二个示例中的故意放置的01100001(Ascii'a')应该没有区别。 Yet, when I run printf, I don't get 100 random outputs. 但是,当我运行printf时,我没有得到100个随机输出。 I get one. 我拿一个 And I don't assume random fields are in general set to '\\0'. 而且我不认为随机字段通常设置为“ \\ 0”。

Which means, my understanding must be wrong somewhere. 这意味着,我的理解在某处一定是错误的。 Please help me understand where I make my mistake. 请帮助我了解我在哪里犯错。

It doesn't, it's undefined behavior. 并非如此,这是未定义的行为。 Your program just accidentally prints the un" expected " value. 您的程序只是意外地打印出un“ 期望的 ”值。

#include <stdio.h>

int main(void)
{
    char test[100];
    printf("%s",test);
    return 0;
}

You can't expect the code above to do anything predictable, it might print something, it could segfault, there is no way to predict what will actually happen because the behavior of such program is strictly undefined. 您不能期望上面的代码做任何可预测的事情,它可能会打印某些内容,可能会出现段错误,由于这种程序的行为是严格未定义的,因此无法预测实际会发生什么。

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

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