为什么指针给出两个不同的地址? [英] Why pointer is giving two different addresses?

查看:67
本文介绍了为什么指针给出两个不同的地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个程序.我有一些疑问.您可以在编译器中运行它.我在 linux 中使用 gcc 编译器

I have this program. And I have some doubts. You can run it in your compiler. I am using gcc compiler in linux

#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;
}

在这段代码中,add 占据了每个数组元素的地址值,并通过循环一一打印该地址.但是add给出的地址值不等于&(a[i][j]) 而这两个给出的值是相等的.也就是说,对于每个数组元素,*add 等于 *(&(a[i][j])).有人能解释一下为什么会这样吗?

In this code add occupies the address value of each array elements and prints that address one by one through loop. 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. That is, *add is equal to *(&(a[i][j])) for each array element. Can some one explain me why this is so?

我打印了每个元素的大小,以确认内存中数据的排列顺序.由于我的编译器基于 32 位,它在 add&(a[i][j]).

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]).

最后打印数组的起始地址.这给出了与 &a[0][0] 相同的地址.所以问题是哪种方法是正确的,add=&(a[i][j]; 还是直接把a[i][j]?

In the last I print the initial address of array. This gives the address same as &a[0][0]. So the question is which method is correct, add=&(a[i][j]; or direct out putting the a[i][j]?

推荐答案

它们是同一个地址.它可能是让您认为它们不同的标志.使用 %p 打印指针或使用 %u 两者.

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.

这篇关于为什么指针给出两个不同的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆