【问题标题】:Indexing an array pointed to by a pointer within a Structure索引结构中指针指向的数组
【发布时间】:2013-01-16 18:11:20
【问题描述】:

看着我的Previous question。我用这组代码得到了解决方案

const MEMBERS *some_members = (MEMBERS *) GET_MEM();
unsigned value1 = some_members->mem1;
unsigned value2 = *some_members->mem2;

没有像我预期的那样工作。但是在样本是一个

的情况下
unsigned sample [4] = {2,5,6,1};

如果我需要从结构中对数组的第三个字符(即 sample [3] =1. )进行索引,我该如何在数组中进行索引。我是否也将 value2 设为指针?

谢谢大家..

【问题讨论】:

  • 不是我很了解这个问题,而是sample[3]==1(索引从零开始)。
  • @AntonKovalenko 谢谢...纠正了。

标签: c arrays pointers type-conversion structure


【解决方案1】:

在这种情况下,是的,将value2 设为指针。也就是说:

const MEMBERS *some_members = (MEMBERS *) GET_MEM();
unsigned value1 = some_members->mem1;
unsigned *value2 = some_members->mem2;

// These are true statements
value2[0] == 2;
value2[1] == 5;
value2[2] == 6;
value2[3] == 1;

【讨论】:

  • 谢谢。但似乎只有 Value_2[0] ==2。其他没有给出实际值...
【解决方案2】:

指针和数组的访问方式相同。

例如:

int array[4] = { 1, 2, 3, 4 };
printf("Third entry in array = %d\n", array[2]);

int *pointer = array;
printf("Third entry in array using pointer = %d\n", pointer[2]);

如果指针是否在结构中无关紧要,只需使用正常的字段访问(例如structure.pointer[2]structpointer->pointer[2])。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 2012-12-07
    • 2016-06-20
    • 1970-01-01
    相关资源
    最近更新 更多