简体   繁体   English

动态内存分配

[英]dynamic memory allocation

here is example how Pointers are used to store and manage the addresses of dynamically allocated blocks of memory 这是如何使用指针存储和管理动态分配的内存块地址的示例

#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;
}

but here is mistakes 但是这里有错误

1 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 ==========

what is wrong?please help 怎么了?请帮忙

Since this is C++, you need to cast the return from malloc as C++ does not automatically convert a void * to a T * : 由于这是C ++,因此您需要转换malloc的返回值,因为C ++不会自动将void *转换为T *

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

Or even better, stop using malloc and use new instead and you won't have to cast: 甚至更好的是,停止使用malloc并改用new而不必强制转换:

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

That said, if you do use new , you need to free with delete : 也就是说,如果您确实使用new ,则需要使用delete

delete[] item->name;
delete item;

Also, if you use new , by default the runtime will inform you about out of memory by throwing an exception. 另外,如果您使用new ,则默认情况下,运行时将通过引发异常来通知您有关内存不足的信息。 While it's best to learn how to deal with exceptions as a temporary stop gap, you can have the nothrow version of new so that it will return 0 when out of memory: 虽然最好学习如何将异常作为临时的停顿间隔进行处理,但是您可以使用new的nothrow版本,以便在内存不足时返回0:

item = new (std::nothrow) Item;

I absolutely agree with previous answers -- if this is going to be used in a C++ program, do it the C++ way. 我完全同意以前的答案-如果要在C ++程序中使用它,请以C ++的方式进行。

Try this: 尝试这个:

#include <iostream>
using namespace std;
struct Item{
    int id;
    string name;
    float cost;
    Item(char *pName) : id(-1), name(pName), cost(0) {}
    };
// Look ma, no "make_item"!

Then, where you would have used make_item: 然后,您将在哪里使用make_item:

    ...
    pItem = make_item("hoozit");
    ...

replace that code with: 将该代码替换为:

    ...
    pItem = new Item("hoozit");
    ...

If you just want to fix your compilation errors... 如果您只想修复编译错误...

Change this: 更改此:

item=malloc(sizeof(struct Item));

To: 至:

item=(item*)malloc(sizeof(struct Item));

and this: 和这个:

item->name=malloc(strlen(name)+1);

To: 至:

item->name=(char*)malloc(strlen(name)+1);

At row 11 item=malloc(sizeof(struct Item)); 在第11行item=malloc(sizeof(struct Item));
must become item=(Item *)malloc(sizeof(struct Item)); 必须成为item=(Item *)malloc(sizeof(struct Item));

At row 20 item->name=malloc(strlen(name)+1); 在第20行的item->name=malloc(strlen(name)+1);
must become item->name=(char *)malloc(strlen(name)+1); 必须成为item->name=(char *)malloc(strlen(name)+1);

At row 21 if (item->name=NULL){ if (item->name=NULL){
must become if (item->name==NULL){ . 必须成为if (item->name==NULL){

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM