首页 > 解决方案 > 如何将新的更改为malloc?

问题描述

我正在将我的语言从 c++ 更改为 c 并想使用 new,但是 c 不允许使用 new,所以我必须使用 malloc。

malloc(sizeof(*ThreadNum))

当我尝试自己做并且没有选择时,上面的行不起作用。这是我希望切换的线路。任何提示都会很可爱:)

for(i=0; i <NUM_THREADS; i++){

ThreadS [i] = new struct ThreadNum; //allocating memory in heap
(*ThreadS[i]).num = num;
(*ThreadS[i]).NumThreads = i;
pthread_t ID;

printf("Creating thread %d\n", i); //prints out when the threads are created

rc = pthread_create(&ID, NULL, print, (void *) ThreadS[i]); //creates the threads

标签: c++c

解决方案


您需要考虑的第一件事是,new并且malloc()不是等价物。第二件事是,ThreadNum所以struct你可能想写sizeof(struct ThreadNum),但通常更好的选择是这样的

ThreadNum *thread_num = malloc(sizeof(*thread_num));

请注意,上面thread_num不是类型或struct,它是一个变量并且具有指针类型。使用*before 意味着您希望类型的大小减少一级间接。

回到我的第一条评论,new它不仅分配内存,而且还调用对象构造函数,这是中不存在的东西。

在 c 中,您必须手动进行所有初始化,并且在检查后malloc()确实返回了一个有效指针。


推荐阅读