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

时间:2015-02-11 22:59:09

标签: c pointers struct

这个问题与我之前的问题有关: 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

1 个答案:

答案 0 :(得分:1)

您正在评估*item.options,而不是item.options。这似乎不是您想要打印的内容(即&#34;选项指针&#34;),因为有一个额外的解除引用操作。