如何使用 C+ 中的指针访问数组中的特定索引

How do i access specific indexes within an array using pointers in C+?

本文关键字:索引 数组 指针 何使用 访问      更新时间:2023-10-16

我正在编写一个程序,可以打印出最多30个数字的斐波那契数列。我必须通过使用指针遍历数组来做到这一点,但我不知道该怎么做。

我能理解的容易遵循的信息并不多。

当我看到 c++ 的代码对此的回答时,我看到的只是这个......

是一个菜鸟,当我必须查看代码时,我很难查看所有"std::"约定。我知道这可能是很好的惯例,但我还不擅长。所以我想要一个简单的例子,假设我在项目中使用using namespace std;行代码。

我试过设置..使用指针变量循环,但我不确定如何做到这一点。

void fibonacciSequence(){
    //initialize the array and users input
    const int ARRAY_SIZE = 30;
    int numbers[ARRAY_SIZE];
    int *pointer;
    pointer = numbers;

    //Traverse the array and generate the Fibonacci Sequence
    for(int i = 0; i < ARRAY_SIZE; i++){
        //Set first element to 0
        if(i == 0){
            numbers[i] = 0;
        }
        //Set second element to 1
        else if (i == 1){
            numbers[i] = 1;
        }
        //Start calculating the sequence after the first 2 elements
        //have been established.
        else{
            numbers[i] = numbers[(i - 1)] + numbers[(i - 2)];
        }
    }
    // Output the Fibonacci Sequence after calculations.
    for(int i = 0; i < ARRAY_SIZE; i++){
        cout << numbers[i] << endl;
    }
}

我拥有的这段代码运行良好。但是,而不是在 for 中使用"i"遍历数组......循环,我需要使用"指针"。

实际上非常简单

改变这个

for(int i = 0; i < ARRAY_SIZE; i++){
    cout << numbers[i] << endl;
}

对此

for(int* p = numbers; p < numbers + ARRAY_SIZE; p++){
    cout << *p << endl;
}

解释

int* p = numbers - 将 p 设置为指向数组的开头

p < numbers + ARRAY_SIZE - 检查 p 是否未到达数组的末尾

p++ - 将 p 移动到数组的下一个元素

*p - 访问 p 指向的元素

与第一个循环类似的更改。

这整个主题都是指针算术,也许你可以做一些研究。

对于学习指针来说,这可能不是一个好的项目,因为索引是计算fibanocci序列的最自然方法。但在这里。将该生成器循环替换为:

int *current = numbers;
*current++ = 0;
*current++ = 1;
while (current != numbers + ARRAY_SIZE) {
    *current = *(current - 1) + *(current - 2);
    ++current;
}

然后对于输出:

for (current = numbers; current != numbers + ARRAY_SIZE; ++current)
    std::cout << *current << 'n';