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;
}
沒有運氣。我是否需要創建一個單獨的函數進行分配?什麼是完成這個最好的方法?謝謝。
在'new_class'中,你也應該檢查第二個malloc返回值,然後檢查'free(c1)'和'return NULL;'是否失敗。如果它不在'new_class()'中完成,它需要在'new_class'之外完成,並且沒有人會記得這樣做。 – 2015-02-10 19:21:02
@BrianMcFarland @BrianMcFarland不一定是因爲畢竟它總是可以檢查'var'成員,儘管你的解決方案意味着在任何階段沒有'malloc'意味着'struct'不能被分配,所以我將使用它, 好點子。 – 2015-02-10 19:24:07
謝謝。當我試圖返回結構的時候,我感到很蠢,因爲函數的返回值顯然是它的指針。 – user1801359 2015-02-10 19:25:54