gpt4 book ai didi

c - 为什么两个不同函数的数组和指针参数的地址相同?

转载 作者:行者123 更新时间:2023-12-04 12:19:34 26 4
gpt4 key购买 nike

我有来自 Peter van der Linden 的 Expert C Programming - Deep C Secrets 第 9 章的以下代码。

char ga[] = "abcdefghijklm";

void my_array_func( char ca[10] )
{
printf(" addr of array param = %#x \n",&ca);
printf(" addr (ca[0]) = %#x \n",&(ca[0]));
}

void my_pointer_func( char *pa )
{
printf(" addr of ptr param = %#x \n",&pa);
printf(" addr (pa[0]) = %#x \n",&(pa[0]));
}

main()
{
printf(" addr of global array = %#x \n",&ga);
printf(" addr (ga[0]) = %#x \n",&(ga[0]));
my_array_func( ga );
my_pointer_func( ga );
}

输出如下:

addr of global array = 0x870f018  
addr (ga[0]) = 0x870f018

addr of array param = 0x574f17c8
addr (ca[0]) = 0x870f018

addr of ptr param = 0x574f17c8
addr (pa[0]) = 0x870f018

我很困惑为什么 addr of array paramaddr of ptr param 是一样的。对于我来说,capa 是两个不同的指针,因此它们的地址应该不同。谁能帮忙解释一下?

对比:

main ()  
{
int a = 1;
int *p1 = &a;
int *p2 = &a;

printf("add of p1 = %#x \n", &p1);
printf("add of p2 = %#x \n", &p2);
}

将给出不同地址的结果:

addr of p1 = 0x50a687e0    
addr of p2 = 0x50a687d8

这两个代码段有什么区别?

最佳答案

I am confused why addr of array param and addr of ptr para are the same. As for me, ca and pa are two different pointers, and thus their addresses should be different. Anyone can help to explain?

这是巧合。

my_array_funcmy_pointer_func 堆栈帧的内存要求是相同的。因此,用于存储参数的地址是相同的。

另外,请记住

void my_array_func( char ca[10] )

相同
void my_array_func( char* ca )

如果在调用 my_pointer_func 之前引入另一层函数,您会发现地址不一样。

#include <stdio.h>

char ga[] = "abcdefghijklm";

void my_array_func( char ca[10] )
{
printf(" addr of array param = 0x%p \n",&ca);
printf(" addr (ca[0]) = 0x%p \n",&(ca[0]));
}

void my_pointer_func( char *pa )
{
printf(" addr of ptr param = 0x%p \n",&pa);
printf(" addr (pa[0]) = 0x%p \n",&(pa[0]));
}

void intermediate_func(char* pa)
{
my_pointer_func( pa );
}

int main()
{
printf(" addr of global array = 0x%p \n",&ga);
printf(" addr (ga[0]) = 0x%p \n",&(ga[0]));
my_array_func( ga );
my_pointer_func( ga );
intermediate_func( ga );
}

输出:

 addr of global array = 0x0x601040 
addr (ga[0]) = 0x0x601040
addr of array param = 0x0x7fffee05cf98
addr (ca[0]) = 0x0x601040
addr of ptr param = 0x0x7fffee05cf98
addr (pa[0]) = 0x0x601040
addr of ptr param = 0x0x7fffee05cf78
addr (pa[0]) = 0x0x601040

关于c - 为什么两个不同函数的数组和指针参数的地址相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32430514/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com