gpt4 book ai didi

c - 指向指针数组的指针指向意外的地址

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

这个问题与我之前的问题相关: Arduino compile error while using reference to a struct in another struct

我将示例代码移植回电脑并编译它以获取线索,出了什么问题。

这是示例:

#include <stdio.h>

unsigned int steps=64;
unsigned int mode=0;
unsigned int speed=1;


typedef struct{
unsigned int option_value;
char option_name[17];
} SELECTION;

typedef struct{
char item_name[17];
unsigned int* variable;
SELECTION** options;
} MENU_ITEM;


SELECTION mode_forward = { 0, "Forward" };
SELECTION mode_backward = { 1, "Backward" };
SELECTION* options_mode[] = { &mode_forward, &mode_backward };

SELECTION speed_slow = { 0, "Slow" };
SELECTION speed_normal = { 1, "Normal" };
SELECTION speed_fast = { 2, "Fast" };
SELECTION* options_speed[] = { &speed_slow, &speed_normal, &speed_fast };

MENU_ITEM menu_steps = { "Steps", &steps, NULL };
MENU_ITEM menu_mode = { "Mode", &mode, options_mode };
MENU_ITEM menu_speed = { "Speed", &speed, options_speed };
MENU_ITEM menu_exit = { "Exit", NULL, NULL };

const unsigned char menu_items = 4;
MENU_ITEM* menu_list[menu_items] = { &menu_steps, &menu_mode, &menu_speed, &menu_exit };
//-----------------------------------------------------------

int main(){

int options;

options=(int)(sizeof(options_speed)/sizeof(options_speed[0]));
printf("Speed options: %i\n\n",options);

printf("Address of speed_slow: %p\n",&speed_slow);
printf("Address of speed_normal: %p\n",&speed_normal);
printf("Address of speed_fast: %p\n",&speed_fast);
printf("Address of array: %p\n\n",&options_speed);

MENU_ITEM item;
item=*menu_list[2];

printf("Menu Item: %s - Item Value: %i\n",item.item_name,*item.variable);
printf("Address of name: %p\n",&item.item_name);
printf("Address of variable-pointer: %p\n",&item.variable);
printf("Address of options-pointer: %p\n",&item.options);
printf("Value of options-pointer: %p\n",*item.options);


return 0;
}

当我启动程序时,我得到以下输出:

Speed options: 3

Address of speed_slow: 0x6010c0
Address of speed_normal: 0x6010e0
Address of speed_fast: 0x601100
Address of array: 0x601120

Menu Item: Speed - Item Value: 1
Address of name: 0x7fff18a5dc90
Address of variable-pointer: 0x7fff18a5dca8
Address of options-pointer: 0x7fff18a5dcb0
Value of options-pointer: 0x6010c0

这就是我所期望的......除了最后一行。它指向的地址不应该是 0x601120 - options_speed 数组的地址吗?为什么它指向数组的第一个成员?我需要更改什么才能让它指向 0x601120

最佳答案

您正在评估*item.options,而不是item.options。这似乎不是您想要打印的内容(即“选项指针”),因为存在额外的取消引用操作。

关于c - 指向指针数组的指针指向意外的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28466213/

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