2016-10-05 48 views
3

我想知道如何將包含一個int數組的結構賦值給一個結構數組。無論我想到什麼新的解決方案,我都會得到不正確的結果。如何正確地將包含int數組的結構賦值給一個struct數組?

我認爲問題就出在這一段代碼:

struct Codes *create(int as) { 
    struct Codes *c = malloc(sizeof (struct Codes)+as * sizeof (int)); 
    c->as = as; 
    for (int i = 0; i < as; i++) { 
     c->a[i] = i; 
    } 

    return c; 
} 

整個代碼:

#include <stdio.h> 
#include <stdlib.h> 
#include <ctype.h> 

struct Codes { 
    int as; 
    int a[]; 
}; 

struct Code { 
    int as; 
    struct Codes *ci[]; 
}; 

struct Codes *create(int as) { 
    struct Codes *c = malloc(sizeof (struct Codes)+as * sizeof (int)); 
    c->as = as; 
    for (int i = 0; i < as; i++) { 
     c->a[i] = i; 
    } 

    return c; 
} 

struct Code *and(int as, struct Codes *cd) { 
    struct Code *c = malloc(sizeof (struct Code)+as * sizeof (struct Codes)); 
    for (int i = 0; i < as; i++) { 
     c->ci[i] = cd; 
    } 
    c->as = as; 
    return c; 
} 

int main(int argc, char **argv) { 

    struct Codes *cd; 
    cd = create(4); 

    struct Code *c; 
    c = and(2, cd); 

    for (int i = 0; i < c->as; i += 1) { 
     for (int j=0; j < c->ci[i]->as; j++) { 
      printf("%d \n", c->ci[i]->a[j]); 
     } 
    } 

    free(cd); 
    free(c); 

}//main 

實際結果:

0 
1 
2 
3 

預期結果:

0 
1 
2 
3 
0 
1 
2 
3 
+1

學習如何使用調試器並能夠在程序運行時通過檢查變量的值來自己找到這些東西是件好事 –

+0

對不起,我不知道我是如何搞砸的,謝謝尋求幫助。 –

回答

1

struct Code *c = malloc(sizeof (struct Code)+as * sizeof (struct Codes));不正確。 struct Code的ci是一個指針數組,但是你爲一個數組結構分配了空間。

爲了解決這個問題,要麼改變對sizeof(struct Codes *),或者最好使用解引用指針你分配空間的類型的模式:

struct Code *c = malloc(sizeof *c + as * sizeof c->ci[0]); 

此外,for (int j;應該for (int j = 0;。您的代碼通過使用未初始化的值j導致未定義的行爲,這只是偶然得到您所做的輸出。使用gcc標誌-Wextra會診斷出這個錯誤。

相關問題