带C的动态内存

Jad*_* Ng -3 c malloc

struct forcePin {
    char _name[512];
};

struct forcePin *_forcePin[500000];    
_forcePin[i] = (struct forcePin *) malloc (sizeof (struct forcePin));
Run Code Online (Sandbox Code Playgroud)

我可以知道如下所示的线路在做什么?

_forcePin[i] = (struct forcePin *) malloc (sizeof (struct forcePin));
Run Code Online (Sandbox Code Playgroud)

我不熟悉c,如果你能告诉我如何使这一行也是C++格式的.谢谢

Som*_*ude 7

动态内存分配在C中非常重要,您应该正确地学习它.

问题的作用是从堆中分配内存,即sizeof(struct forcePin)字节.该malloc函数返回指向此分配内存的通用指针,并将该指针指定给指针_forcePin[i].

关于该行一件事,你应该不是类型转换的返回值malloc的功能.


在C++中,您使用该new语句来分配指针:

_forcePin[i] = new forcePin;
Run Code Online (Sandbox Code Playgroud)

但是,在C++中使用指针和动态堆分配是不受欢迎的.我建议你使用std::vector非指针结构:

struct forcePin {
    std::string name;
};

std::vector<forcePin> forcePin;
forcePin.push_back(forcePin{});
Run Code Online (Sandbox Code Playgroud)