简体   繁体   English

C ++指针组成一个数组

[英]C++ pointers to make an array

I am new to C++ ... I am playing with pointers ... This code uses a char ptr as an array . 我是C ++的新手,我在玩指针。此代码使用char ptr作为数组。

#‎include‬<iostream>
using namespace std;

int main (){

    cout << "Playground "<<endl;

    const short max=10;

    char * str=new char ;

    for (short i=0;i<max;i++)
        *(str+i)=char(i+100);

    for (short i=0;i<max;i++)
        cout <<str+i<< char(3) <<endl;

    for(short i=0;i<max;i++)
        delete (str+i);

    return 0;
}

But I am not sure if delete (str+i) works or not , and why ? 但是我不确定delete(str + i)是否有效,为什么? But I think it does not work because I have run the program many times and although the string is printed : 但我认为它不起作用,因为我已经多次运行了该程序,尽管该字符串已打印出来:

Playground
defghijklm
efghijklm
fghijklm
ghijklm
hijklm
ijklm
jklm
klm
lm
m

I have this error message 我有此错误消息

try #0
*** Error in `./p': free(): invalid pointer: 0x09d90009 ***
Aborted (core dumped)

try #1
*** Error in `./p': free(): invalid pointer: 0x08453009 ***
Aborted (core dumped)

try #2
*** Error in `./p': free(): invalid pointer: 0x0863c009 ***
Aborted (core dumped)

etc ...

Because the invalid pointer keep changing , I have the feeling that the objects has not been deleted or garbage collected and every time I run the code I use another area of the memory ... 因为无效指针不断变化,所以我感觉对象没有被删除或垃圾回收,每次运行代码时,我都使用内存的另一个区域...

Finally I am starting to get why regular array are better ... 终于我开始明白为什么常规数组更好了...

*from the beginning a contiguous space in memory is reserved for the data *从一开始就在内存中为数据保留连续的空间

*not need to worry about delete ... *无需担心删除...

Those are just my guesses... 这些只是我的猜测...

You have out of bound access: 您的访问权限不受限制:

char* str = new char; // single element

should be 应该

char* str=new char[max]; // array of char

and you have to release memory with 你必须用释放内存

delete [] str;

but to avoid to manage memory manually, you may use std::string or std::vector<char> 但是为了避免手动管理内存,可以使用std::stringstd::vector<char>

You are only making one dynamic memory allocation, and for just 1 char, but you are deleting dynamically allocated memory multiple times in the last for-loop - you can only do one delete for every new. 您只进行一次动态内存分配,并且只分配了1个字符,但是您在最后一个for循环中多次删除了动态分配的内存-您只能对每个新的内存执行一次删除。

Additionally, in the first for-loop you assign new char values to memory outside of what you allocated, which means you are overwriting memory that isn't yours. 此外,在第一个for循环中,您将新的char值分配给分配的内存之外的内存,这意味着您将覆盖非您拥有的内存。

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

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