gpt4 book ai didi

c++ - 如何将 new 更改为 malloc?

转载 作者:太空宇宙 更新时间:2023-11-04 05:22:53 25 4
gpt4 key购买 nike

我正在将我的语言从 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

最佳答案

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

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

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

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

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

关于c++ - 如何将 new 更改为 malloc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52637472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com