c - 对动态数组中的每个进行操作

标签 c arrays loops memory foreach

假设我有一个结构

struct point_2d {
    int x,
    int y
};

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

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

    ...
}

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

是否有一种方法可以在不知道数组长度的情况下进行循环(例如使用字符串,递增指针直到遇到 \0),或者我是否需要进一步输入来确定那个长度?

最佳答案

Is there a way to loop through without having to know the length of the array (such as with strings, incrementing the pointer until \0 is encountered), or do I need further input to determine that length?

如果不知道循环多远,就无法循环,除非您向数组添加一个标记值,就像使用 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() 循环相比,这几乎不需要编写更多内容,并且您可以准确地看到发生了什么。

关于c - 对动态数组中的每个进行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26164036/

相关文章:

javascript - bootstrap-select 初始化时 Vue 循环不工作

c - 将二维字符数组与函数一起使用

java - 最长的数字序列

javascript - 计算对象数组内的数组数量

Linux/Bash - 为 "find"创建循环以输出到文件

python - 如何在数据框列中 append 值

c - 获取日期并将其保存在结构体 C 中

c++ - 在 C/C++ Windows API 中使用 Void 函数

c - 位掩码困惑

android - 从字符串数组填充 ListView