gpt4 book ai didi

c++ - 这是 C++ 中带有指针的数组的良好使用/代码吗?

转载 作者:行者123 更新时间:2023-11-28 01:26:27 24 4
gpt4 key购买 nike

我想问你是否考虑过这段代码,它是完全糟糕还是我对内存的使用不当

这是代码

// Ask for capacity
int capacity ;
cout << "capacity: ";
cin >> capacity;

// Declare the array with pointers, this line is very important
int *arr = new int;

// For 0 until capacity-1 print ask for the numbers
for (int i = 0; i < capacity; i++)
{
cout << "number: ";
cin >> *(arr + i);
}

// Print them
for (int i = 0; i < capacity; i++)
{
cout << "[" << i << "]: " << *(arr + i) << " in " << arr + i << endl;
}

这是它的输出示例

capacity: 9
number: 1
number: 2
number: 3
number: 4
number: 5
number: 6
number: 7
number: 8
number: 9
[0]: 1 in 0x55dee480c690
[1]: 2 in 0x55dee480c694
[2]: 3 in 0x55dee480c698
[3]: 4 in 0x55dee480c69c
[4]: 5 in 0x55dee480c6a0
[5]: 6 in 0x55dee480c6a4
[6]: 7 in 0x55dee480c6a8
[7]: 8 in 0x55dee480c6ac
[8]: 9 in 0x55dee480c6b0

看,它有效地将数字保存在内存中的正确位置(4 位,一个 int 的大小)但限制是什么?我怎么知道我是否正在触摸我不应该触摸的内存?因为看,我将数组声明为

int *arr = new int

可以吗?

与此代码相同,但这可能会更糟一些,因为它是一个字符串,您可能知道的一个字符数组

// Declaring the pointer name as new char and ask for it
char *name = new char;
cout << "name in: ";
cin >> name;
cout << "name out\n";
for (int i = 0; *(name + i) != '\0' ; i++)
{
printf("[%i]: %c\n", i, *(name + i));
}

例子:

name in: Gilberto       
name out
[0]: G
[1]: i
[2]: l
[3]: b
[4]: e
[5]: r
[6]: t
[7]: o

最佳答案

代码只分配了一个int目的。修复:

int* arr = new int[capacity];

*(arr + i)可以更简单:arr[i] .


代码最后需要删除数组:

delete[] arr;

或者,更好的是,使用智能指针来避免手动删除:

std::unique_ptr<int[]> arr(new int[capacity]);

或者,更好的是,使用 std::vector<int> arr(capacity); .

关于c++ - 这是 C++ 中带有指针的数组的良好使用/代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53562770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com