By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
428,601 Members | 989 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 428,601 IT Pros & Developers. It's quick & easy.

Pointers and array names basics

P: 4
Expand|Select|Wrap|Line Numbers
  1.  
  2. # include <iostream>
  3. using namespace std;
  4.  
  5. int main (void)
  6. {
  7. int arr[5],*arrf;
  8. arrf=arr+5;
  9. cout<<arr<<endl<<arrf<<endl;
  10. for(;arr<=arrf;arr=arr+1)
  11. {
  12. cout<<arr<<endl;
  13. cin>>*arr;
  14. }
  15. }
  16.  
I am just trying to understand some concepts of pointers and array names here. What I am trying to do is access elements of the array using the array name as a pointer to the first element of the array.

I get the following compile error:
error: incompatible types in assignment of ‘int*’ to ‘int [5]’

Can someone explain the reason behind this?
Sep 3 '10 #1
Share this Question
Share on Google+
4 Replies


Banfa
Expert Mod 5K+
P: 8,916
The problem is this arr=arr+1 in your for loop. You can not assign to arrays only to array elements. If you want to loop through an array either use a pointer which you can increment or use an integer index which you can also increment.

Also this arrf=arr+5; sets arrf to point just past the end of the array.
Sep 3 '10 #2

P: 4
Dear Banfa,

I wasnt trying a value to assign to an array, I was just trying to increment the pointer pointing to the first element of the array.
The mistake I made was using the pointer arr, which was the pointer pointing to the first element of the array as well as the array name.
The following code rectifies that and might help in understanding what I was actually trying to do.

Thanks anyways for your comments. Appreciate it.

Expand|Select|Wrap|Line Numbers
  1.  
  2. # include <iostream>
  3. using namespace std;
  4.  
  5. int main (void)
  6. {
  7.  
  8.         int arr[5],*arrf;
  9.         arrf=arr;
  10.         for( ;arrf < arr+5;arrf=arrf+1)
  11.         {
  12.                 cout<<"Input the value to be stored at memory location "<<arrf<<endl;
  13.                 cin>>*arrf;
  14.         }
  15.  
  16.  
  17.         for ( int k = 0; k<5; k++)
  18.                 cout<<"arr["<<k<<"] = "<<arr[k]<<endl;
  19.         return 0;
  20.  
  21. }
  22.  
Sep 3 '10 #3

100+
P: 542
Yeees....I`m not sure. The array name is in fact a pointer to the first element of the array. So with int Moo[5] if Moo is called it will point to the value of an int in Moo[0].
Sep 4 '10 #4

weaknessforcats
Expert Mod 5K+
P: 9,197

Post your reply

Sign in to post your reply or Sign up for a free account.