[英]Array Pointer in C++
int n;
int *array[8]
cout<<"Enter Number Between 0-9 Only"<<endl;
for(int i = 0; i< 9; i++){
cout << "Enter Number " << (i + 1) << endl;
cin >> n;
if((n >= 0) && (n <= 9))
array[i] = &n;
else {
cout << "Numbers from 0-9 only\n" << endl;
i--;
}
}
cout << *array[0] << endl;
}
I'm trying to store 9 entered numbers in a pointer array but its not working why?? 我正在尝试将9个输入的数字存储在指针数组中,但是为什么不起作用? Can you explain why to me and how to solve it or improve it.
您能否向我解释为什么以及如何解决或改进它。 I'm just a beginner and its not homework im testing what i had read.
我只是一个初学者,它不是家庭作业,无法测试我阅读的内容。
The line 线
array[i] = &n;
will store the same address in every entry in your array. 将在阵列的每个条目中存储相同的地址。 This is just pointing to
n
so will always point to that value. 这只是指向
n
因此将始终指向该值。
Either define the array as an array of integers 将数组定义为整数数组
ie int array[9];
即
int array[9];
and then place the value into that array 然后将值放入该数组
ie array[i] = n;
即
array[i] = n;
OR 要么
Allocate some memory off the heap 从堆中分配一些内存
ie 即
int *array[9];
...
array[i] = new int;
*array[i] = n;
But you will then have to free this memory with delete
to avoid a memory leak. 但是您随后必须使用
delete
释放此内存,以避免内存泄漏。
There are several issues here. 这里有几个问题。
I would have something more like *NB not compiled and run) 我会有更多类似* NB的东西无法编译和运行)
{
...
std::vector<int> array;
cout<<"Enter Number Between 0-9 Only"<<endl;
for(int i = 0; i< 8; i++){
int n;
cout << "Enter Number " << (i + 1) << endl;
cin >> n;
if((n >= 0) && (n <= 9))
array.push_back(n);
else {
cout << "Numbers from 0-9 only\n" << endl;
i--;
}
}
cout << array[0] << endl;
}
您正在将指向n的指针保存在数组中,但是您不断更改n的值。
You don't really need to mess with pointers here. 您真的不需要在这里弄乱指针。 Change your array definition, how you populate it, and how you display and you should have better luck.
更改数组定义,填充方式以及显示方式,您应该会遇到更好的运气。
int array[9];
...
array[i] = n;
...
cout << array[0] << endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.