gpt4 book ai didi

数组名称的 C 内存位置

转载 作者:行者123 更新时间:2023-11-30 14:54:23 25 4
gpt4 key购买 nike

我对 C 如何在内存中存储数组感到困惑。从下面的示例中,str1 的地址等于它的值。我将结果解释为:内存地址 &str1 包含地址本身的值。但事实并非如此,因为从其他示例中我看到 str1 的地址包含字符串的第一个值,在本例中为“H”。

所以我的问题是:str1的地址存储在哪里?

#include <stdio.h>

int main(int argc, char const *argv[]) {
char str1[] = "Hello World";
printf("%d %d %c\n",&str1,str1,str1[0] );
return 0;
}

最佳答案

首先,您必须使用%p用于打印地址(指针)的格式说明符。

话虽如此,引用 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.

所以,基本上,

  printf("%p", str1);
printf("%p", &str1[0]);

是一样的。

现在,进入 &str1 的部分,嗯,类型不同。它的类型为 char [<array size>] .

关于数组名称的 C 内存位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46791521/

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