为什么数组的地址等于它在 C 中的值?

编程入门 行业动态 更新时间:2024-10-27 14:20:05
本文介绍了为什么数组的地址等于它在 C 中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

在以下代码中,指针值和指针地址与预期不同.

In the following bit of code, pointer values and pointer addresses differ as expected.

但数组值和地址不是!

这怎么可能?

输出

my_array = 0022FF00
&my_array = 0022FF00
pointer_to_array = 0022FF00
&pointer_to_array = 0022FEFC

#include <stdio.h>

int main()
{
  char my_array[100] = "some cool string";
  printf("my_array = %p\n", my_array);
  printf("&my_array = %p\n", &my_array);

  char *pointer_to_array = my_array;
  printf("pointer_to_array = %p\n", pointer_to_array);
  printf("&pointer_to_array = %p\n", &pointer_to_array);

  printf("Press ENTER to continue...\n");
  getchar();
  return 0;
}

推荐答案

数组名通常取数组第一个元素的地址,所以array&array 具有相同的值(但类型不同,所以 array+1&array+1 相等,如果数组长度超过 1 个元素).

The name of an array usually evaluates to the address of the first element of the array, so array and &array have the same value (but different types, so array+1 and &array+1 will not be equal if the array is more than 1 element long).

对此有两个例外:当数组名称是 sizeof 或一元 & (address-of) 的操作数时,名称指的是数组对象本身.因此,sizeof array 为您提供整个数组的字节大小,而不是指针的大小.

There are two exceptions to this: when the array name is an operand of sizeof or unary & (address-of), the name refers to the array object itself. Thus sizeof array gives you the size in bytes of the entire array, not the size of a pointer.

对于定义为T array[size]的数组,其类型为T *.当/如果你增加它,你会得到数组中的下一个元素.

For an array defined as T array[size], it will have type T *. When/if you increment it, you get to the next element in the array.

&array 计算为相同的地址,但给定相同的定义,它创建一个 T(*)[size] 类型的指针——即,它是指向数组的指针,而不是指向单个元素的指针.如果你增加这个指针,它会增加整个数组的大小,而不是单个元素的大小.例如,使用这样的代码:

&array evaluates to the same address, but given the same definition, it creates a pointer of the type T(*)[size] -- i.e., it's a pointer to an array, not to a single element. If you increment this pointer, it'll add the size of the entire array, not the size of a single element. For example, with code like this:

char array[16];
printf("%p\t%p", (void*)&array, (void*)(&array+1));

我们可以期望第二个指针比第一个大 16 个(因为它是一个 16 个字符的数组).由于 %p 通常以十六进制转换指针,因此它可能看起来像:

We can expect the second pointer to be 16 greater than the first (because it's an array of 16 char's). Since %p typically converts pointers in hexadecimal, it might look something like:

0x12341000    0x12341010

这篇关于为什么数组的地址等于它在 C 中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-16 07:02:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/881903.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   它在   地址

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!