Accessing array elements in c

纵然是瞬间 提交于 2021-02-16 14:54:11

问题


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

1 value required as increment operator.

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;
}

回答1:


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

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:

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


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]);
}

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
}

For further reading on pointer arithmetic : here




回答2:


While arrays can decay to pointers to their first element (which is what happens when you use e.g. *arr) it is not a pointer in itself.

You also can not change an array, change where it "points", which is what is wrong with arr++, it is roughly the same as arr = arr + 1 and while arr + 1 is allowed the assignment back to arr is not, you can't change the location of an array.

If you want to do like you do, then you need an actual pointer, initialize it to point to the location of the first element of arr, and use the pointer in the loop instead.




回答3:


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

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

arr++ not working.because of array is constant pointer and you can't increment the address. so alway remember array name represent as base address then If you want to increment then give extra argue with that.see the above example.




回答4:


The increment operator is applied on the value of a variable. The value of an array is its elements, so what would you expect the increment operator to do? Increment each element in the array? The value of a pointer variable, on the other hand, is an address, so the increment operator applies here.




回答5:


You can't using operator ++ for arrays. Array is are constant pointer to data and can't be modified.



来源:https://stackoverflow.com/questions/37584648/accessing-array-elements-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!