如何将新更改为 malloc?

How to change new to malloc?

本文关键字:malloc 新更改      更新时间:2023-10-16

我正在将我的语言从 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 %dn", i); //prints out when the threads are created
rc = pthread_create(&ID, NULL, print, (void *) ThreadS[i]); //creates the threads

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

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

注意上面thread_num不是类型或struct,它是一个变量,具有指针类型。在它前面使用*表示您希望类型的大小少一个间接级别。

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

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