如何在C中的数组的任意点初始化多个结构?

问题描述 投票:0回答:2

我在 C 中定义了一个结构


struct problem_spec_point {
        int point_no;
        double x;
        double y;
        int bc;
};

我有一个长度为 6 的结构数组,前四个结构在初始化时明确定义。

static struct point points[6] =
    {
        {0, 1, 2, 5},
        {0, 1, 2, 6},
        {0, 1, 2, 7},
        {0, 1, 2, 8},
    };

我可以稍后添加第5个和第6个结构:

points[4] = (struct point) {0,1,2,12}; points[5] = (struct point) {3,3,3,3}; 
但是假设我想同时添加这两个(或多个)连续结构。 有点像

points[4] = {(struct point) {0,1,2,12}, (struct point) {3,3,3,3},}; 
有没有这样的方法来做到这一点?

显然我尝试了上面列出的语法。

对于上下文,实际上我的代码有一个长度为 3n+6 的数组。我有一个 for 循环为前 3n 个结构分配它们的值,但最后 6 个有不同的奇怪模式。

for(int i = 0; i < 3n; i++)
{
 point[i] = stuff;
}

//odd points here at end of array

我可以切换顺序并进行一些索引更改:

static struct point points[3n+6] = 
{
  last points first
}

for(int i = 6; i < 3n+6, i++
{
  point[i]=stuff;
}

但我不想。我对C不是很熟悉,我很好奇。

第一次发帖,如有不妥之处请见谅

arrays c struct initialization
2个回答
3
投票

最好的方法可能只是用简单易读的代码输入它:

points[4] = (struct point) {0,1,2,12};
points[5] = (struct point) {3,3,3,3};

或者对于具有相同值等的大间隔,使用

memcpy
。也许是这样的:

#include <string.h>

void add_points (struct point* points, const struct point* val, size_t from, size_t to)
{
  for(size_t i=from; i<=to; i++)
  {
    memcpy(&points[i], val, sizeof(struct points));
  }
}


// usage example: assign {3,3,3,3} from index 4 to index 5

add_points(points, &(struct point){3,3,3,3}, 4, 5);

(可以使用

restrict
指针稍微优化此代码。)


0
投票

Lundin 正确地告诉您可以使用

memcpy
。他没有明确提到您可以针对不同的值重新表述您的尝试

points[4] = {(struct point) {0,1,2,12}, (struct point) {3,3,3,3},};

memcpy
喜欢

    memcpy(points+4, (struct point []){ {0,1,2,12}, {3,3,3,3} },
              sizeof (struct point [2]));
© www.soinside.com 2019 - 2024. All rights reserved.