Pointers and array names basics

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rm84
    New Member
    • Sep 2010
    • 4

    Pointers and array names basics

    Code:
     
    # include <iostream>
    using namespace std;
    
    int main (void)
    {
    int arr[5],*arrf;
    arrf=arr+5;
    cout<<arr<<endl<<arrf<<endl;
    for(;arr<=arrf;arr=arr+1)
    {
    cout<<arr<<endl;
    cin>>*arr;
    }
    }
    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?
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    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.

    Comment

    • rm84
      New Member
      • Sep 2010
      • 4

      #3
      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.

      Code:
       
      # include <iostream>
      using namespace std;
      
      int main (void)
      {
      
              int arr[5],*arrf;
              arrf=arr;
              for( ;arrf < arr+5;arrf=arrf+1)
              {
                      cout<<"Input the value to be stored at memory location "<<arrf<<endl;
                      cin>>*arrf;
              }
      
      
              for ( int k = 0; k<5; k++)
                      cout<<"arr["<<k<<"] = "<<arr[k]<<endl;
              return 0;
      
      }

      Comment

      • whodgson
        Contributor
        • Jan 2007
        • 542

        #4
        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].

        Comment

        • weaknessforcats
          Recognized Expert Expert
          • Mar 2007
          • 9214

          #5
          Read this: http://bytes.com/topic/c/insights/77...rrays-revealed

          Comment

          Working...