gpt4 book ai didi

c - 为什么我不能将指针作为参数传递?

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

我正在尝试通过 c 中的函数检索指针。如果指针是函数的返回值,那么它就可以工作。但是,如果我将指针的地址传递给函数,则无法从函数内部更新取消引用的指针值(应该是存储在指针中的地址)。

请查看代码和输出。为什么我使用 GetPointer1()GetPointer2() 得到的结果不同?我错过了什么?

#include <stdio.h>
#include <stdint.h>

uint8_t SrcArray[2][3] = {{11,12,13},{21,22,23}};
uint8_t *p1;
uint8_t *p2;

void GetPointer1(uint8_t *p);
uint8_t* GetPointer2(void);

int main()
{
printf ("&SrcArray[0][0]: %d\n", &SrcArray[0][0]);

GetPointer1(p1);
p2 = GetPointer2();

printf ("p1: %d\n",p1);
printf ("p2: %d\n",p2);

return 0;
}

void GetPointer1(uint8_t *p)
{
p = &SrcArray[0][0];
}

uint8_t* GetPointer2(void)
{
return &SrcArray[0][0];
}

输出:

&SrcArray[0][0]: 6295604
p1: 0
p2: 6295604

最佳答案

那是因为您在 GetPointer1(uint8_t *p) 函数签名中的指针是按值传递的。如果要修改指针本身,则必须将指针传递给指针:

void GetPointer1(uint8_t **p) {
*p = &SrcArray[0][0];
}

否则,您可以修改指针指向的片内存,但不能修改指针本身。

关于c - 为什么我不能将指针作为参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36029843/

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