c - Array 和 Array[0] 混淆
问题描述
在以下 C 代码中:
char test[] ={'T','e','s','t'};
printf("%d\n",test == &test[0]); // Returns 1 - Okay as array varaible holds address of first element
那么以下内容不应该打印相同的内容吗?:
printf("value of test %c\n", test); // prints - '|' not even in the array
printf("value of test[0] %c\n", test[0]); // prints - 'T'
即便如此,即使这些打印出不同的值:
printf("value of test %p\n", test); // contains a address 0x7ffee9b22b7c
printf("value of test[0] %p\n", test[0]); // also conatains 0x100
怎么了?
谢谢
解决方案
您在第一个示例中回答了您自己的问题:
test == &test[0]
test != test[0] // otherwise, test[0] would have to be equal to &test[0]
即(解释为指针)的值等于的地址。因此,您的以下示例不可能是正确的,因为这意味着对于其中任何一个,它的值都将等于它自己的地址,这是没有意义的!test
test[0]
(注:以下地址当然是示例。)
表达 | 类型 | 值解释为字符%c |
值解释为指针%p |
---|---|---|---|
test |
char* |
荒谬的 | 0x1000 |
&test |
char** |
荒谬的 | 0x2000 |
test[0] |
char |
T |
荒谬的 |
&test[0] |
char* |
荒谬的 | 0x1000 |
test[1] |
char |
e |
荒谬的 |
&test[1] |
char* |
荒谬的 | 0x1001 |
test[2] |
char |
s |
荒谬的 |
&test[2] |
char* |
荒谬的 | 0x1002 |
test[3] |
char |
t |
荒谬的 |
&test[3] |
char* |
荒谬的 | 0x1003 |
注意:为了理解您最初的问题,可以将test
视为char*
,因此&test
视为char**
。然而,实际上它有点复杂,test
实际上是 type char(*)[4]
。例如,这会有所不同sizeof
。
推荐阅读
- c# - C# - Asp.net Web API 测试项目 - 如何模拟用户并在特定用户下运行测试用例
- c# - log4net.Appender 中缺少 AdoNetAppender 类
- spring-boot - 使用 H2 和 JPA 的 Spring Boot 集成测试失败
- reactjs - 反应 - 未找到模块
- sails.js - 从 Sails + swagger autogenation 中删除一些路线
- python - 在 Keras 的 ImageDataGenerator.flow_from_directory 中处理无效/损坏的图像文件
- reporting-services - 合并 SSRS 中的行
- rust - 为什么在调试和发布模式下存储和加载 AVX2 256 位向量会产生不同的结果?
- c - 完成前程序退出
- powershell - 使用powershell检查文件内容是否存在