gpt4 book ai didi

c - 我想知道这段代码内部发生了什么?

转载 作者:行者123 更新时间:2023-12-02 06:46:58 25 4
gpt4 key购买 nike

我想知道这段代码的内部处理过程。

char arr[] = "cat";
*arr = 'b';
printf("%s",arr);

在这段代码中,数组中的 c 是如何被 b 覆盖的?

Output : bat

最佳答案

如果有助于理解,*arr*(&arr[0])注意是一样的,即存储在索引 0 处的值。

您只是为其分配一个新值。

以图形方式:

char arr[] = "cat";

+-------+--------+--------+--------+     
| c | a | t | \0 |
+-------+--------+--------+--------+
arr[0] arr[1] arr[2] arr[3]

之后

*arr = 'b';   // which is practically same as arr[0] = 'b';

+-------+--------+--------+--------+   
| b | a | t | \0 |
+-------+--------+--------+--------+
arr[0] arr[1] arr[2] arr[3]

注意:

引用 C11,章节 §6.3.2.1

Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. [...]

关于c - 我想知道这段代码内部发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57097983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com