C 如何在运行时为结构数组赋值?

C 如何在运行时为结构数组赋值?,c,struct,variable-assignment,C,Struct,Variable Assignment,我声明了一个struct数组,并在编译时初始化了它 现在,出于单元测试的目的,我想从一个可以从main()和单元测试调用的函数中初始化它 出于某种原因,可能涉及到16小时的编码马拉松和疲劳,我无法理解。所以假设你有 struct foo { int a; int b; }; struct foo foo_array[5] = { { 0, 0 }, { 1, 1 }, { 2, 2 } }; int main() { memcpy(foo_array, some_

我声明了一个struct数组,并在编译时初始化了它

现在,出于单元测试的目的,我想从一个可以从main()和单元测试调用的函数中初始化它

出于某种原因,可能涉及到16小时的编码马拉松和疲劳,我无法理解。

所以假设你有

struct foo {
   int a;
   int b;
};

struct foo foo_array[5] = {
 { 0, 0 }, { 1, 1 }, { 2, 2 }
};


int main() { 
     memcpy(foo_array, some_stuff, sizeof(foo_array)); // should work
    ...
或者你可以:

int main() {
    int i;
    for ( i = 0; i < sizeof(foo_array)/sizeof(struct foo); i++ ) {
           init(&foo_array[i]);
    }
}
intmain(){
int i;
对于(i=0;i
但是如果不看你的代码,很难说是什么引起了麻烦。。。我敢肯定,你可能忽略了一些非常琐碎的事情,因为你已经累了,而且已经做了16个小时。

看这个:

struct Student
{
    int rollNo;
    float cgpa;
};

int main()
{
    const int totalStudents=10;

    Student studentsArray[totalStudents];

    for(int currentIndex=0; currentIndex< totalStudents; currentIndex++)
    {
          printf("Enter Roll No for student # %d\n" , currentIndex+1);
          scanf("%d\n", &studentsArray[currentIndex].rollNo);

          printf("Enter CGPA for student # %d\n", currentIndex+1);
          scanf("%d\n", &studentsArray[currentIndex].cgpa);
     }
}
struct学生
{
int-rollNo;
浮动cgpa;
};
int main()
{
const int totalStudents=10;
学生人数(学生总数);
对于(int currentIndex=0;currentIndex 1)这是C++代码而不是C代码。2) 这对于单元测试没有用处;3) 这不是家庭作业
typedef struct {
  int ia;
  char * pc;
} St_t;

void stInit(St_t * pst) {
  if (!pst)
    return;

  pst->ia = 1;
  pst->pc = strdup("foo");

  /* Assuming this function 'knows' the array has two elements, 
     we simply increment 'pst' to reference the next element. */
  ++ pst;

  pst->ia = 2;
  pst->pc = strdup("bar");

}

void foo(void) {
  /* Declare 'st' and set it to zero(s)/NULL(s). */
  St_t st[2] = {{0}, {0}};

  /* Initialise 'st' during run-time from a function. */
  stInit(st);

  ...
}