2015-02-10 54 views
0

在下面的代碼中,我如何以及在哪裏動態初始化類結構中的數組?例如,如果我將它改爲double * var,malloc語句去哪兒?如何在「面向對象」C中動態初始化數組?

myclass.h

#ifndef MYCLASS_H 
#define MYCLASS_H 

struct Class; 

struct Class *new_class(); 
void class_function(struct Class*,double); 

#endif 

myclass.c

#include "myclass.h" 
#include <stdlib.h> 

struct Class { 
    double var; 
}; 

struct Class *new_class() 
{ 
    return (struct Class *)malloc(sizeof(struct Class)); 
} 

void class_function(struct Class *inst, double num) 
{ 
    inst->var = num; 
} 

的main.c

#include "myclass.h" 

int main() 
{ 
    struct Class *c1 = new_class(); 
    class_function(c1,0.15); 
    return 0; 
} 

我試圖修改new_class功能類似

struct Class *new_class(int len) 
{ 
    Class c1 = (struct Class *)malloc(sizeof(struct Class)); 
    c1.var = (double)malloc(len*sizeof(double)); 
    return c1; 
} 

沒有運氣。我是否需要創建一個單獨的函數進行分配?什麼是完成這個最好的方法?謝謝。

回答

2

這應該工作,首先struct定義修改爲

struct Class 
{ 
    double *var; 
    size_t len; 
}; 

然後

struct Class *new_class(int len) 
{ 
    struct Class *c1; 
    c1 = malloc(sizeof(struct Class)); 
    if (c1 == NULL) 
     return NULL; 
    c1->var = malloc(len * sizeof(double)); 
    if (c1->var == NULL) 
    { 
     free(c1); 
     return NULL; 
    } 
    c1->len = len; 

    return c1; 
} 

class_function()應檢查指針NULL,相信我,你會感謝我在這對此的未來

void set_class_value(struct Class *inst, int index, double num) 
{ 
    if ((inst == NULL) || (inst->var == NULL) || (index < 0) || (index >= inst->len)) 
     return; 
    inst->var[index] = num; 
} 

你也可以有

double get_class_value(struct Class *inst, int index) 
{ 
    if ((inst == NULL) || (inst->var == NULL) || (index < 0) || (index >= inst->len)) 
     return 0.0; /* or any value that would indicate failure */ 
    return inst->var[index]; 
} 

你必須有一個函數來釋放資源,當你完成

void free_class(struct Class *klass) 
{ 
    if (klass == NULL) 
     return; 
    free(klass->var); 
    free(klass); 
} 

現在main()

int main() 
{ 
    struct Class *c1; 
    c1 = new_class(5); 
    if (c1 == NULL) 
    { 
     perror("Memory exhausted\n"); 
     return -1; 
    } 
    set_class_value(c1, 0, 0.15); 
    printf("%f\n", get_class_value(c1, 0)); 

    free_class(c1); 
    return 0; 
} 

這個我覺得應該幫助,雖然沒有太多的解釋,我認爲代碼本身就是說話。

注意,我添加了一個len場的結構,因爲否則就沒有任何意義有一個struct通過了解元素的數組中就可以防止數量的大小來存儲double數組,因此問題,您還應該瞭解不透明類型以及如何從結構用戶隱藏結構定義,以便強制使用安全。

+0

在'new_class'中,你也應該檢查第二個malloc返回值,然後檢查'free(c1)'和'return NULL;'是否失敗。如果它不在'new_class()'中完成,它需要在'new_class'之外完成,並且沒有人會記得這樣做。 – 2015-02-10 19:21:02

+0

@BrianMcFarland @BrianMcFarland不一定是因爲畢竟它總是可以檢查'var'成員,儘管你的解決方案意味着在任何階段沒有'malloc'意味着'struct'不能被分配,所以我將使用它, 好點子。 – 2015-02-10 19:24:07

+0

謝謝。當我試圖返回結構的時候,我感到很蠢,因爲函數的返回值顯然是它的指針。 – user1801359 2015-02-10 19:25:54