gpt4 book ai didi

c - 指针的作用类似于局部变量,并且不会在函数中保留其修改

转载 作者:行者123 更新时间:2023-11-30 16:11:48 29 4
gpt4 key购买 nike

我有一个指针,它指向A,我将这个指针传递给一个函数,在函数中,指针改变并指向 B ,当函数结束时,指针值恢复回来并指向A,这是为什么?

int device_num = 0;
int display_devices_size = 3;
DISPLAY_DEVICE* display_devices = (DISPLAY_DEVICE*)malloc(sizeof(DISPLAY_DEVICE) * display_devices_size);
get_display_devices(display_devices,&display_devices_size,&device_num);

void get_display_devices(DISPLAY_DEVICE* display_devices, int* display_devices_size, int* device_num)
{
DISPLAY_DEVICE d;
d.cb = sizeof(DISPLAY_DEVICE);
while (EnumDisplayDevices(NULL, *device_num, &d, 0))
{
//After the first call to EnumDisplayDevices DispDev.DeviceString contains graphic card's name.
//After the second call DispDev.DeviceString contains monitor's name.
if (*device_num >= *display_devices_size)
{
DISPLAY_DEVICE* temp = (DISPLAY_DEVICE*)realloc(display_devices, (*display_devices_size) * sizeof(DISPLAY_DEVICE) * 2);
if (temp != NULL)
{
display_devices = temp;
*display_devices_size = *display_devices_size * 2;
}
}
display_devices\[(*device_num)\] = d;
(*device_num)++;
}

}

详情如下截图:
before function
in function
after function

最佳答案

如果你想更新指针,你需要传递指针的地址,而不是它的内容。您的代码在子例程中分配一个新指针,但这对原始指针没有影响。编辑了下面的代码 - 我没有检查它是否可以编译,但您可以看到更改。

int device_num = 0;
int display_devices_size = 3;
DISPLAY_DEVICE* display_devices = (DISPLAY_DEVICE*)malloc(sizeof(DISPLAY_DEVICE) * display_devices_size);

// Pass the ADDRESS of display_devices

get_display_devices(&display_devices,&display_devices_size,&device_num);

// Function takes a pointer to a pointer as the first argument.

DISPLAY_DEVICE* get_display_devices(DISPLAY_DEVICE** display_devices, int* display_devices_size, int* device_num)
{
DISPLAY_DEVICE d;
d.cb = sizeof(DISPLAY_DEVICE);
while (EnumDisplayDevices(NULL, *device_num, &d, 0))
{
//After the first call to EnumDisplayDevices DispDev.DeviceString contains graphic card's name.
//After the second call DispDev.DeviceString contains monitor's name.
if (*device_num >= *display_devices_size)
{
DISPLAY_DEVICE* temp = (DISPLAY_DEVICE*)realloc(*display_devices, (*display_devices_size) * sizeof(DISPLAY_DEVICE) * 2);
if (temp != NULL)
{
*display_devices = temp;
*display_devices_size = *display_devices_size * 2;
}
}
(*display_devices)[*device_num] = d;
(*device_num)++;
}

}

关于c - 指针的作用类似于局部变量,并且不会在函数中保留其修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58496404/

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