简体   繁体   English

为什么指针给出两个不同的地址?

[英]Why pointer is giving two different addresses?

I have this program. 我有这个程序。 And I have some doubts. 我有些怀疑。 You can run it in your compiler. 您可以在编译器中运行它。 I am using gcc compiler in linux 我在Linux中使用gcc编译器

#include<stdio.h>
int main()
{
    int j=4,*add;
    int i=2;
    int a[i][j];
    for (i=0;i<=1;i++)
    {
        for(j=0;j<=3;j++)
        {
            scanf("%d",&a[i][j],"%d",&a[i][j]);
        }
    }
    for(i=0;i<=1;i++)
    {
        for (j=0;j<=3;j++)
        {
            add=&(a[i][j]);
            printf("\nSize of %d is %d and address is: %u that should be equal to: %d",a[i][j],sizeof(a[i][j]),&(a[i][j]),add);//Address are not equal while add is having the value of &(a[i][j])
            printf("\nSize of %d is %d and value is: %d that should be equal to: %d",a[i][j],sizeof(a[i][j]),*(&(a[i][j])),*add);//Here value at both addresses are same
        }
     }

    printf("\n initial address of the array is: %u that should be equal to address given by &a[0][0]",&a); //And it's equal

return 0;
}

In this code add occupies the address value of each array elements and prints that address one by one through loop. 在此代码中, add占用每个数组元素的地址值,并逐个循环打印该地址。 But address value given by add is not equal to the one given by &(a[i][j]) while the values give by these two are equal. 但是add给出的地址值不等于&(a[i][j])给出的地址值,而这两者给出的值相等。 That is, *add is equal to *(&(a[i][j])) for each array element. 也就是说,对于每个数组元素, *add等于*(&(a[i][j])) Can some one explain me why this is so? 有人可以解释一下为什么会这样吗?

I printed the size of each element so as to confirm the sequence of data arrangement in memory. 我打印了每个元素的大小,以确认内存中数据排列的顺序。 As my compiler 32-bit based, it printed the addresses by the gap of 4 bits in case of both add and &(a[i][j]) . 作为我的基于32位的编译器,在add&(a[i][j])情况下,它以4位的间隔打印地址。

In the last I print the initial address of array. 最后,我打印数组的初始地址。 This gives the address same as &a[0][0] . 这给出的地址与&a[0][0] So the question is which method is correct, add=&(a[i][j] ; or direct out putting the a[i][j] ? 因此,问题是哪种方法是正确的,请add=&(a[i][j] ;还是直接列出a[i][j]

they are the same address. 他们是相同的地址。 It might be the sign that makes you think they are different. 这可能是使您认为它们不同的标志。 Use %p to print the pointer or use %u for both. 使用%p打印指针或使用%u两者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM