简体   繁体   中英

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.

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. 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 *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. 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 .

In c you have to do all the initialization by hand and after checking that malloc() did return a valid pointer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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