Reputation: 53
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
Upvotes: 0
Views: 132
Reputation: 53006
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 c.
In c you have to do all the initialization by hand and after checking that malloc()
did return a valid pointer.
Upvotes: 7