如何使用 C+ 中的指针访问数组中的特定索引
How do i access specific indexes within an array using pointers in C+?
我正在编写一个程序,可以打印出最多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';
相关文章:
- 特征获取索引数组,其中向量中的值为真(不需要循环)
- 是否可以使用字符串或字符索引数组
- 为什么在使用字符索引数组时会出现这种不同的行为
- 在具有重复索引的索引数组处更改 ArrayFire 数组
- 使用索引数组订购 ArrayFire Array 的最佳方式
- C++ 中结构的动态索引数组
- 1索引数组上的qsort()正在扰乱索引
- C++ 索引数组打印和删除字符串名称 数组打印
- 字符串下标超出范围.我不知道如何使用字符索引数组,所以我使用了(无符号整数),但它不起作用
- openGL drawElements - 一个额外的三角形,使用索引数组
- 具有索引数组的地形(高度贴图)LOD
- 通过创建索引数组进行 C++ 排序
- OpenGL:两个顶点数组 + 两个索引数组
- 将索引数组排序为主数组
- 自动循环跳过某些索引数组
- 为静态强制转换的索引数组生成数组
- 重载枚举索引数组的std::get
- 使用c++中的第二个索引数组对数组进行排序
- 给定的零索引数组 &该数组的均衡索引
- CUDA:重新索引数组