简体   繁体   English

C ++中的数组指针

[英]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. 这里有几个问题。

  1. You have nowhere to store the values. 您无处存储值。 You have an array of 8 pointers which are all set to point to the same variable n, which is on the stack and so goes out of scope. 您有一个由8个指针组成的数组,所有这些指针都设置为指向同一变量n,该变量位于堆栈上,因此超出范围。
  2. The array has 8 elements so the loop goes one past the end 该数组有8个元素,因此循环结束了一个循环
  3. This is C++ so really best not to use C arrays unless you have a justifiable reason to. 这是C ++,因此,除非有合理的理由,否则最好不要使用C数组。

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.

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