C语言 如何在运行时赋值给struct数组



我声明了一个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]);
    }
}

但是如果不看你的代码,很难说是什么引起了麻烦…我敢肯定,你可能忽略了一些非常琐碎的事情,因为你已经累了,而且已经做了16个小时了。

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);
  ...
}

看这个:

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 # %dn" , currentIndex+1);
          scanf("%dn", &studentsArray[currentIndex].rollNo);
          printf("Enter CGPA for student # %dn", currentIndex+1);
          scanf("%dn", &studentsArray[currentIndex].cgpa);
     }
}

最新更新