这里是指针如何用于存储和管理动态分配的内存块的地址的示例
#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;
}
Run Code Online (Sandbox Code Playgroud)
但这是错误
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 ==========
Run Code Online (Sandbox Code Playgroud)
有什么问题?请帮忙
由于这是C++,因此需要从malloc转换返回值,因为C++不会自动将a转换void *为T *:
item=static_cast<Item *>(malloc(sizeof(struct Item)));
Run Code Online (Sandbox Code Playgroud)
或者甚至更好,停止使用malloc和使用new,你不必投射:
item = new Item;
item->name = new char[strlen(name + 1)];
Run Code Online (Sandbox Code Playgroud)
也就是说,如果你使用new,你需要释放delete:
delete[] item->name;
delete item;
Run Code Online (Sandbox Code Playgroud)
此外,如果您使用new,默认情况下,运行时将通过抛出异常来通知您内存不足.虽然最好学习如何处理异常作为临时停止间隙,但你可以使用nothrow版本,new以便在内存不足时返回0:
item = new (std::nothrow) Item;
Run Code Online (Sandbox Code Playgroud)