2011-11-26 88 views
2

我聲明瞭一個struct數組並在編譯時初始化它。如何在運行時將值賦給一個struct數組?

現在,爲了進行單元測試,我想從一個函數中初始化它,我可以從main()和我的單元測試中調用它。

出於某種原因,可能涉及16小時編碼馬拉松&用盡,我無法弄清楚。

+3

你可以分享代碼片段? –

回答

3

因此,假如你有

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個小時。

0

看到這樣一條:

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); 
    } 
} 
+0

1)這是C++代碼而不是C代碼。 2)這對於單元測試是沒有用的; 3)這不是功課 –

1
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); 

    ... 
}