【问题标题】:What is the difference in C between &i and i if i is an array of integers? [duplicate]如果 i 是整数数组,在 C 中 &i 和 i 有什么区别? [复制]
【发布时间】:2013-07-29 12:36:21
【问题描述】:

如果i 是一个数组,我尝试了一个代码来查看&ii 之间的区别。我的假设是i 代表数组的起始地址,我不知道如果我也打印&i 会发生什么。 结果令人惊讶(对我来说),因为i&i 都是数组的起始地址。

#include<stdio.h>

int main()
{
    char str[25] = "IndiaBIX";

    int i[] = {1,2,3,4};

    printf("%i\n", &i);
    printf("%i\n", i);
    return 0;
}

结果将是:

2686692  
2686692

这是同一个地址。

但是如果我使用指向 int 的指针:

#include<stdio.h>
#include <stdlib.h>

int main()
{
    int *j = (int *) malloc(sizeof(int));
    *j = 12;

    printf("%i %i %i\n", *j,j,&j);
    return 0;
}

结果将是:

12
5582744
2686748

这里我假设第一个是j指向的内存区域的值,第二个是j指向的内存区域的地址,第三个是指针本身的内存地址。如果我打印i&amp;i,为什么&amp;i不是指针i的内存地址?

【问题讨论】:

标签: c arrays pointers memory-address


【解决方案1】:
int i[] = {1,2,3,4};

区别在于它们的类型,i 是整数数组类型,&amp;i 是整数数组指针类型。

【讨论】:

    【解决方案2】:

    是的,i 和 &i 都会导致打印相同的答案,但它们并不完全相同,

    -> i 表示名为 i 的数组中第一个元素的地址。
    -> &i 表示整个数组的地址(虽然两者的值相同,但它们的类型不同)

    更多信息,请参考这个[链接]http://publications.gbdirect.co.uk/c_book/chapter5/arrays_and_address_of.html

                        int ar[10];
                        ip = ar;                /* address of first element */
                        ip = &ar[0];            /* address of first element */
                        ar10i = &ar;            /* address of whole array */
    

    【讨论】:

      猜你喜欢
      • 2017-10-23
      • 2011-08-06
      • 2013-05-22
      • 1970-01-01
      • 2010-10-11
      • 2014-12-25
      • 2011-03-21
      • 2021-08-25
      相关资源
      最近更新 更多