Iterating through C-style array not using a pointer

岁酱吖の 提交于 2019-12-05 16:11:29
Coding Mash

You are getting this error as you trying to increment the array. It is invalid because in c++, the name of the array can be implicitly converted to a constant pointer to the very first index. You cannot increment an array, because an array is a container and incrementing a container makes no sense.

To answer your question completely, I would need to explain some things. Let me try and others can add in.

Remember there are three types of constant pointers.

1.Pointer to a constant memory location. This is a normal pointer but it points to a variable which is constant by nature (read only variable infact). It means that the value of variable it is pointing to cannot be changed through it. Normally it is used point a constant variable like this.

const int x = 10 ;
const int *ptr = & x ; 

here, you cannot do *ptr = 5 ; because the pointer is pointing to a constant variable.

2.Const pointer to a memory location. This is a pointer which can point to only one memory location throughout the program. The value of the variable it is pointing to can be changed but the pointer itself is constant. It is declared like this.

int x = 10, y = 5 ;
int * const ptr = &x ;

you cannot do ptr = &y ; later in the program. Array can be implicitly converted to a constant pointer to a memory location as well. So it cannot be incremented or decremented in this way. (You can read about it here if you like: What is array decaying?)

3.Constant pointer to a constant memory location. This is a pointer which is constant itself and points to a constant memory location as well. it is declared like this.

const int x = 8 ;
const int * const ptr = &x ;

It means that neither you can point the pointer to anywhere except the initialized location, and you cannot even change the value of the location it is pointing to.

I hope the concept is very much clear by now. Now to your question: you want to print the array through pointer arithmetic, but you cannot increment the array itself. So one solution to do this is to make another pointer (a normal one) and assign it the address of the array’s first index. Then you can increment, decrement or change the value of that array. Something like this.

int arr [] = {1, 2, 3, 4, 5} ;
int *ptr = arr ;
for (int i = 0 ; i < 5 ; i++)
{
    cout << *ptr << " " ;
    ptr++ ;
}

So you could always do:

int arr [] = {1, 2, 3, 4, 5} ; 
int *a = arr;
for (int i = 0 ; i < 5 ; i++) 
{     
  cout << *a ;     
  a++ ; 
} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!