【问题标题】:Do operation on each in dynamic array对动态数组中的每个进行操作
【发布时间】:2014-10-02 15:15:56
【问题描述】:

假设我有一个struct

struct point_2d {
    int x,
    int y
};

假设在我的程序中我保留了一个这种类型的数组,

main()
{
    struct point_2d *coords = malloc(10*sizeof(struct point_2d));

    ...
}

我想对它们中的每一个进行操作(例如,将所有点的坐标设置为原点或其他东西)。

有没有办法在不知道数组长度的情况下循环遍历(例如使用字符串,递增指针直到遇到\0),还是我需要进一步输入来确定该长度?

【问题讨论】:

    标签: c arrays loops memory foreach


    【解决方案1】:

    有没有一种方法可以循环遍历而不必知道数组的长度(例如使用字符串,递增指针直到遇到 \0),还是我需要进一步输入来确定该长度?

    在不知道循环多远的情况下无法循环,除非您将标记值添加到数组中,就像使用 C 字符串和 \0 终止一样。即使是 C++ 中的 foreach() 循环也必须获取一个越过容器末尾的迭代器才能知道循环多远。

    假设你分配了内存

    int size = 10;
    struct point_2d* coords = malloc(size*sizeof(*coords));
    

    我建议使用以下循环结构之一遍历数组:

    • 转发:

      for(int i = 0; i < size; i++) coords[i].x = coords[i].y = 0;
      
    • 向后:

      for(int i = size; i--; ) coords[i].x = coords[i].y = 0;
      

    这并不比用其他语言编写 foreach() 循环多,而且您可以准确地看到正在发生的事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-03
      • 2013-01-14
      • 1970-01-01
      • 2012-04-18
      • 2019-06-23
      • 2018-05-13
      • 1970-01-01
      相关资源
      最近更新 更多