在C中访问数组元素 [英] Accessing array elements in c

查看:66
本文介绍了在C中访问数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是在代码块中编译此代码的代码,我得到以下错误消息:

Below is the code on compiling this code in codeblocks I get the following error message:

需要1个值作为增量运算符.

现在我知道 arr ++ 无法正常工作,但我想知道为什么.

Now I know that arr++ is not working but I want to know why.

#include<stdio.h>
int main()
{
  int arr[5]={1,2,3,4,5},i;

  for(i=0;i<5;i++)
  {
    printf("%d\n",*arr);
    arr++;
  }
  return 0;
}

推荐答案

arr ++无法正常工作,但我想知道为什么吗?

arr++ is not working but i want to know why?

arr 存储的基本地址为& arr [0] ,因此, arr 始终指向数组的起始位置,并且不能更改 .这就是 arr ++ 无效且不起作用的原因.

arr stores the base address that is &arr[0] therefore, arr always points to the starting position of the array and can't be changed. that's the reason why arr++ is invalid and doesn't work.

解决方案:

Solution:

您可以在 * (引用运算符)运算符的帮助下使用 arr 来打印数组元素

you can instead use arr with the help of * (referencing operator) operator to print the array elements

for(i=0;i<5;i++)
{
    printf("%d\n",*(arr+i)); 
    //pointer arithmetic *(arr+i)=*(&arr[0]+i*sizeof(data_type_of_arr))
}

在这里, 指针算术 有助于理解

here, pointer arithmetic is helpful to understand

否则,为了打印数据,请改用索引 i :

or else, in order to print the data instead use the index i this way :

for(i=0;i<5;i++)
{
    printf("%d\n",arr[i]);
}


另一种实现方法是考虑指向& arr [0] 并递增的新指针.


One more way to do it is to consider a new pointer to &arr[0] and increment.

int *p=&arr[0];
for(i=0;i<5;i++)
{
    printf("%d\n",*p);
    p++;
    //pointer arithmetic *(p)=*((&p)+1*sizeof(data_type_of_arr))
    //NOTE: address of p updates for every iteration
}


有关指针算术的进一步阅读:此处

这篇关于在C中访问数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆