C++ dynamically allocated memory

前端 未结 8 1906
难免孤独
难免孤独 2020-12-10 16:16

I don\'t quite get the point of dynamically allocated memory and I am hoping you guys can make things clearer for me.

First of all, every time we allocate memory we

8条回答
  •  萌比男神i
    2020-12-10 16:56

    For a single integer it only makes sense if you need the keep the value after for example, returning from a function. Had you declared someInt as you said, it would have been invalidated as soon as it went out of scope.

    However, in general there is a greater use for dynamic allocation. There are many things that your program doesn't know before allocation and depends on input. For example, your program needs to read an image file. How big is that image file? We could say we store it in an array like this:

    unsigned char data[1000000];
    

    But that would only work if the image size was less than or equal to 1000000 bytes, and would also be wasteful for smaller images. Instead, we can dynamically allocate the memory:

    unsigned char* data = new unsigned char[file_size];
    

    Here, file_size is determined at runtime. You couldn't possibly tell this value at the time of compilation.

提交回复
热议问题