如何将新更改为 malloc?
How to change new to 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 %dn", 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
,它是一个变量,具有指针类型。在它前面使用*
表示您希望类型的大小少一个间接级别。
回到我的第一条评论,new
不仅分配内存,而且还调用对象构造函数,这是 c 中不存在的东西。
在 c 中,您必须手动执行所有初始化,并在检查malloc()
确实返回了有效的指针后。
相关文章:
- C++,创建新对象时类的对象更改
- 如何将新更改为 malloc?
- 将 malloc 转换为新的正确方法
- QTree查看新行,没有布局就不可见已更改
- 正在调试 malloc():新内存损坏
- 我怎样才能代替使用新的使用malloc翻译
- 插入新键时,它会更改现有键值的地址吗?
- 重建 exe 时如何自动链接新的静态库而不更改源文件?
- 有没有一种优雅的方法可以使用向量修改器并获得新的向量,而不是更改原始向量
- 指针(指向指针)和新/malloc 向量(向量内部)c++
- C++用一个新类初始化二维向量;默认值更改
- 内存碎片会减慢新/malloc
- 在 Omnet++ 中的模拟时间内更改/设置节点的新位置
- 将 malloc 转换为新的或 std::vector
- 如何在Qt中打开新窗口的情况下更改UI?
- 如何在python中创建等效的结构并使用malloc更改空指针的引用
- 在使用新操作员和C 中的结构的调用构造函数时,获得内存损坏(Malloc)
- C++新运算符是否在下面使用 malloc()
- 将 malloc 更改为新运算符
- 修改xml文件中的任何数据,并通过C++程序保存带有新更改的文件