gpt4 book ai didi

c - 在 C 中直接传递变量地址和传递指针(指向同一变量)之间的区别?

转载 作者:行者123 更新时间:2023-11-30 19:00:21 25 4
gpt4 key购买 nike

我想知道为什么当使用语句 (*func_list_x32_x64[2]) (ptr_64); 调用函数 uint_x64_read 时不起作用(我没有得到任何警告或错误我的程序都会退出),但在使用 (*func_list_x32_x64[2]) (&var_64);

时运行正常

func_ptr.h:

typedef enum {
FUNC_PTR_SUCCESS = 0,
FUNC_PTR_FAIL
} FUNC_PTR_STATUS;

typedef FUNC_PTR_STATUS (*func_ptr)(void *);

FUNC_PTR_STATUS uint_x32_read(void *);

FUNC_PTR_STATUS uint_x32_write(void *);

FUNC_PTR_STATUS uint_x64_read(void *);

FUNC_PTR_STATUS uint_x64_write(void *);

main.c 文件:

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

#include "func_ptr.h"

static func_ptr func_list_x32_x64[] = {
(func_ptr) uint_x32_read,
(func_ptr) uint_x32_write,
(func_ptr) uint_x64_read,
(func_ptr) uint_x64_write,
NULL
};



void main() {
uint8_t usr_option = 0;
uint32_t var_32 = 0;
uint32_t *ptr_32;
uint64_t var_64 = 0;
uint64_t *ptr_64;

ptr_32 = &var_32;
ptr_64 = &var_64;

while (1) {
printf("Enter option: ");
scanf("%d", &usr_option);

if(usr_option == 0)
(*func_list_x32_x64[0]) ((void *)ptr_32);

else if(usr_option == 1)
(*func_list_x32_x64[1]) ((void *)ptr_32);

else if(usr_option == 2) {
(*func_list_x32_x64[2]) (ptr_64);
}

else if(usr_option == 3) {
(*func_list_x32_x64[3]) (ptr_64);
}

else
break;
}
}

func_ptr.c:

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


#include "func_ptr.h"


/**
* @def Defines #UINT_X32_ADDR_VAL as 2000
*/
#define UINT_X32_ADDR_VAL (2000u)

/**
* @def Defines #UINT_X64_ADDR_VAL as 4000
*/
#define UINT_X64_ADDR_VAL (4000u)



FUNC_PTR_STATUS uint_x32_read(void *data_32) {

*(uint32_t *) data_32 = UINT_X32_ADDR_VAL;
return FUNC_PTR_SUCCESS;

}



FUNC_PTR_STATUS uint_x64_read(void *data_64) {

*(uint64_t *) data_64 = 45;
return FUNC_PTR_SUCCESS;

}


FUNC_PTR_STATUS uint_x32_write(void *data_32) {

printf("Val: %d\n", *(uint32_t *) data_32);
return FUNC_PTR_SUCCESS;

}


FUNC_PTR_STATUS uint_x64_write(void *data_64) {

printf("Val: %d\n", *(uint64_t *)data_64);
return FUNC_PTR_SUCCESS;

}

编辑:添加了最少的可重现代码

最佳答案

您的代码存在导致未定义行为的错误。

scanf("%d", &usr_option);

printf("Val: %d\n", *(uint32_t *)data_32);

printf("Val: %d\n", *(uint64_t *)data_64);

void main()

应该是

#include <inttypes.h>

scanf("%" SCNu8, &usr_option);

printf("Val: %" PRIu32 "\n", *(uint32_t *)data_32);

printf("Val: %" PRIu64 "\n", *(uint64_t *)data_64);

int main(void)

始终启用并注意编译器的警告。 (我使用 -Wall -Wextra -pendatic 来表示 gcc。)

关于c - 在 C 中直接传递变量地址和传递指针(指向同一变量)之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60005243/

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