C字符指针长度 [英] C char pointer length

查看:128
本文介绍了C字符指针长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Coursera的测验(未评分).问题是,以下代码可能会评估什么?正确的答案是127和0(其他选项分别是崩溃,-1、128.为什么以下代码可能评估为0?我理解为什么它将评估为127.它是否像未初始化的char字节一样简单,因此它也可以计算为0到127之间的任何数字吗?

This was a quiz (not graded) on Coursera. The question was, what does the following code possibly evaluate to? The correct answers were 127 and 0 (other options were crash, -1, 128. Why does the following code possibly evaluate to 0? I understand why it would evaluate to 127. Is it just as simple as the char bytes are uninitialized and therefore random? Can it also possibly evaluate to any # between 0 and 127?

int foo(void) {

    char bar[128];

    char *baz = &bar[0];

    baz[127] = 0;

    return strlen(baz);

}

推荐答案

以前,此答案的信息有误,这种情况下不会调用修改后的答案:

TL; DR 我们无法提供确切的答案,代码中包含不确定的行为.

TL;DR We cannot have a definitive answer, the code contains indeterministic behavior.

为了详细说明,char bar[128];是一个自动局部变量,如果未显式初始化,则将包含 indeterminate 值.

To elaborate, char bar[128]; is an automatic local variable and if not initialized explicitly, will contain indeterminate values.

引用C11,第§6.7.9章

Quoting C11, chapter §6.7.9

如果未自动初始化具有自动存储期限的对象,则其值为 不定. [....]

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. [....]

在代码中,您只为数组的一个成员分配了值,索引为127.其余元素仍然具有不确定的值.

In your code, you have assigned value for only one member of the array, at index 127. Remaining elements still have indeterminate value.

试图将该数组(基本上是指向数组第一个元素的指针)传递给strlen(),导致读取这些值(寻找空终止符),并且由于不确定的值,不能保证它会在任何 specific 位置找到空终止符.

Attempt to pass that array (pointer to the first element of the array, basically) to strlen(), causes a read on those values (in search of a null-terminator) and due to the indeterminate values, there's no guarantee that it will find the null-terminator at any particular location.

  • 可以很好地在第一个元素中找到一个空终止符(ASCII值0)并返回0.
  • 在最后一个数组元素中返回127之前,它在其他任何数组元素中也找不到任何空终止符(ASCII值0).
  • 它可以在数组中的任何地方找到一个空终止符,然后返回该计数.

因此,这个问题没有明确的答案.

So, there's no definite answer for this question.

注意: (是为了弥补我的错误理解,以防止读者进一步陷入同一困境)

在这里,读取未初始化的值(即不确定的值)不会调用未定义的行为,就像人们可能会想到的那样.

Here, reading the uninitialized values (i.e., indeterminate values) does not invoke undefined behaviour, as one may think.

一个衬里:地址用于对象.

有关此主题的详细讨论,请参见此处.

There's a detailed discussion on this topic, refer here.

这篇关于C字符指针长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆