简体   繁体   English

如何将新的更改为malloc?

[英]How to change new to malloc?

I am changing my language from c++ to c and want to use new, however, c doesn't allow the use of new, so i have to use malloc. 我将语言从c ++更改为c,并希望使用new,但是c不允许使用new,因此我必须使用malloc。

malloc(sizeof(*ThreadNum))

the line above does not work when i tried to do it myself and have run out of options. 当我自己尝试并且已用完所有选项时,上面的行不起作用。 This is the line that i wish to switch. 这是我希望切换的行。 Any tips would be lovely:) 任何提示都将很可爱:)

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

First thing you need to consider is that new and malloc() are not equivalents. 您需要考虑的第一件事是newmalloc()不是等效项。 Second thing is that ThreadNum is a struct so you may want to write sizeof(struct ThreadNum) but usually a better choice is like this 第二件事是ThreadNum是一个struct因此您可能需要编写sizeof(struct ThreadNum)但通常更好的选择是这样的

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

note that above thread_num is not a type or struct , it's a variable and has pointer type. 请注意,上面的thread_num不是type或struct ,而是变量,并且具有指针类型。 Using * before it means that you want the size of the type with one less level of indirection. 在此之前使用*表示您希望类型的大小与间接级别相比少一个。

Getting back to my first comment, new does not only allocate memory but it also invokes the object constructor, which is something that does not exist in . 回到我的第一条评论中, new不仅分配内存,而且还调用对象构造函数,这在中不存在。

In c you have to do all the initialization by hand and after checking that malloc() did return a valid pointer. 在c中,您必须手动进行所有初始化,并在检查malloc()确实返回了有效的指针之后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM