c++ - 如何将新的更改为malloc?
问题描述
我正在将我的语言从 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
解决方案
您需要考虑的第一件事是,new
并且malloc()
不是等价物。第二件事是,ThreadNum
所以struct
你可能想写sizeof(struct ThreadNum)
,但通常更好的选择是这样的
ThreadNum *thread_num = malloc(sizeof(*thread_num));
请注意,上面thread_num
不是类型或struct
,它是一个变量并且具有指针类型。使用*
before 意味着您希望类型的大小减少一级间接。
回到我的第一条评论,new
它不仅分配内存,而且还调用对象构造函数,这是c中不存在的东西。
在 c 中,您必须手动进行所有初始化,并且在检查后malloc()
确实返回了一个有效指针。
推荐阅读
- python - 使用pyarrow读取保存为镶木地板的DataFrame,将文件名保存在列中
- c++ - c++中makefile在清理时出错,找不到文件
- c - 在函数中分配内存,然后在外部使用
- reactjs - 我无法启动 React 项目,因为 node_models 文件丢失但它们存在
- flutter - 为什么选定的值没有反映在 showModalBottomSheet 中?
- angular - 无论时区如何,都使用绝对日期
- tree - ggtree:彩色树枝和尖端
- substrate - 错误[E0658]:非内置内部属性不稳定
- php - 在 null 上调用成员函数 getBag() - Laravel
- r - 仅通过增加 R 中的升序来过滤组