2015-02-10 46 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