gpt4 book ai didi

c++ - 动态内存分配

转载 作者:太空宇宙 更新时间:2023-11-04 15:10:12 24 4
gpt4 key购买 nike

这里是如何使用指针来存储和管理动态分配的内存块地址的示例

#include <iostream>
#include <stdio.h>
using namespace std;
struct Item{
int id;
char* name;
float cost;
};
struct Item*make_item(const char *name){
struct Item *item;
item=malloc(sizeof(struct Item));
if (item==NULL)
return NULL;
memset(item,0,sizeof(struct Item));
item->id=-1;
item->name=NULL;
item->cost=0.0;

/* Save a copy of the name in the new Item */
item->name=malloc(strlen(name)+1);
if (item->name=NULL){
free(item);
return NULL;
}

strcpy(item->name,name);
return item;

}

int main(){



return 0;
}

但是这里有错误

1

>------ Build started: Project: dynamic_memory, Configuration: Debug Win32 ------
1> dynamic_memory.cpp
1>c:\users\david\documents\visual studio 2010\projects\dynamic_memory\dynamic_memory.cpp(11): error C2440: '=' : cannot convert from 'void *' to 'Item *'
1> Conversion from 'void*' to pointer to non-'void' requires an explicit cast
1>c:\users\david\documents\visual studio 2010\projects\dynamic_memory\dynamic_memory.cpp(20): error C2440: '=' : cannot convert from 'void *' to 'char *'
1> Conversion from 'void*' to pointer to non-'void' requires an explicit cast
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

怎么了?请帮忙

最佳答案

因为这是 C++,你需要强制转换 malloc 的返回,因为 C++ 不会自动将 void * 转换为 T *:

item=static_cast<Item *>(malloc(sizeof(struct Item)));

或者更好的是,停止使用 malloc 并使用 new 代替,您将不必强制转换:

item = new Item;
item->name = new char[strlen(name + 1)];

也就是说,如果您确实使用了new,则需要使用delete 释放:

delete[] item->name;
delete item;

此外,如果您使用 new,默认情况下,运行时会通过抛出异常来通知您内存不足。虽然最好学习如何处理异常作为一个临时的权宜之计,但您可以使用 new 的 nothrow 版本,以便它在内存不足时返回 0:

item = new (std::nothrow) Item;

关于c++ - 动态内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3347904/

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