在 C 和 C++ 中创建点数组

Creating array of points in C and C++

本文关键字:创建 数组 C++      更新时间:2023-10-16

有不同的方法可以达到相同的目的,但这基本上是我想做的:

typedef struct point_t {
    unsigned int x;
    unsigned int y
} point_t;

point_t points[64] = { {23, 67}, {123, 9}, {55, 0} ... }

我只想创建一个 xy 坐标的常量数组并像这样读取它们:

i = points[0].x
j = points[0].y

这在 C 和 C++ 中有效吗?

您在声明结构时遇到语法错误,unsigned int y后缺少分号 ,无论如何,检查它是否有效的最好方法是使用 C/C++ 编译器,例如,尝试编译并运行这个:

#include <math.h>
#include <stdio.h>
typedef struct point_t {
    unsigned int x;
    unsigned int y;
} point_t;
int main(int argc, char *argv[]) {
    point_t points[64] = {{23, 67}, {123, 9}, {55, 0}};
    for (int i = 0; i < 64; i++) {
        printf("%d %dn", points[i].x, points[i].y);
    }
}

您应该看到您如何填充前 3 个点,其余的结构数组将被 0 填充。