【问题标题】:c loop through struct array in reversec反向循环遍历struct数组
【发布时间】:2016-11-11 09:36:47
【问题描述】:

我正在尝试反向循环遍历structs 的数组,但不太清楚如何去做。这就是我正常循环的方式:

    struct Thing* ptr = things;
    struct Thing* endPtr = things + sizeof(things)/sizeof(things[0]);

    for(ptr < endPtr)
    {
        // do stuff
    }

【问题讨论】:

  • 什么是things?为什么不使用 indexes 来代替循环呢?
  • ptr[(sizeof(things)/sizeof(things[0]))-1] 是最后一个元素,所以从那个开始到 0 索引...
  • for”.... 新的“while”。
  • @WhozCraig #define for while。奇迹般有效。它还允许我做do {...} for (ptr &lt; endPtr); :)
  • 通过消除for 语句的正常使用来模糊代码是一个非常糟糕的主意。实际上,发布的代码无法编译,这一行:struct Thing* endPtr = things + sizeof(things)/sizeof(things[0]); 产生一个指向数组末尾的指针,而不是指向最后一个元素的指针

标签: c arrays reverse


【解决方案1】:

假设N &gt;= 0,即您的things 序列的项目大小,您当然可以使用索引,但实际上您只需要一个指针:

struct Thing *ptr = things + N;
while (ptr != things)
{
    --ptr;

    // do something with *ptr;
}

【讨论】:

  • @IanAbbott 从技术上讲,您不能使用 while 表达式中的后减来缩短它。我只问了两个关于 SO 的问题,one of them directly relating to that very subject. 很难理解,最终的减量实际上调用了 UB。正是出于这个原因,我选择了这篇文章中的代码。
  • 是的,我在发表评论后才意识到我的错误并删除了它。 (作为参考,我建议在测试中减少 ptrwhile (ptr-- != things)。问题是最终的减少使 ptr 小于 things,即 UB,正如 WhozCraig 所提到的。)跨度>
  • @IanAbbott 我很确定while (ptr != things &amp;&amp; --ptr) 工作,但是,因为在短路评估中会跳过减量。然而,对于任何审查代码的人来说,这将是奇怪的神秘。
  • @WhozCraig 有趣,我最近刚刚向您的-- post 询问了一个类似的++ question
【解决方案2】:

这可能是一个可能的解决方案

 // assuming 'Thing' is the structure in question and 'size' is the length of array
struct Thing array[size];   // created an array of structure Thing having length equals size

struct Thing *ptr;  // pointer of type struct Thing 
ptr = array;
ptr = ptr + (size-1); // point the pointer to last element of the array
int i; //counter

for( i=0; i < size; i++ )
{
    // do something with the pointer ptr
    ptr--; 
}

【讨论】:

  • 您的ptr = ptr + ... 调用未定义的行为。 ptr 在其值与该赋值的右侧表达式一起获取时是不确定的。无论如何,尺寸计算都是错误的。指针算术已经跨越了指向对象类型的大小。
  • ptr 应该在使用前初始化。您在 UB 中对结果进行编程。
【解决方案3】:

可以在向下计数循环中使用指针,但我会优先考虑可读性:

size_t size = sizeof(things) / sizeof(things[0]);

for(size_t i=0; i<size; i++)
{
  size_t index = size - i - 1;
  things[index] = something;
}

【讨论】:

    猜你喜欢
    • 2018-03-09
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    相关资源
    最近更新 更多