Deleting a pointer in C++

后端 未结 6 1363
旧巷少年郎
旧巷少年郎 2020-11-28 01:11

Context: I\'m trying to wrap my head around pointers, we just saw them a couple of weeks ago in school and while practicing today I ran into a silly? issue, it can be super

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 01:56

    Pointers are similar to normal variables in that you don't need to delete them. They are removed from memory at the end of a functions execution and/or the end of the program.

    You can however use pointers to allocate a 'block' of memory, for example like this:

    int *some_integers = new int[20000]
    

    This will allocate memory space for 20000 integers. Useful, because the Stack has a limited size and you might want to mess about with a big load of 'ints' without a stack overflow error.

    Whenever you call new, you should then 'delete' at the end of your program, because otherwise you will get a memory leak, and some allocated memory space will never be returned for other programs to use. To do this:

    delete [] some_integers;
    

    Hope that helps.

提交回复
热议问题