the subscript operator

This is a discussion on the subscript operator within the C++ Programming forums, part of the General Programming Boards category; Hello, So, I didnt know I could do this: Code: int main() { const int ARRAYSIZE = 10; int myArray[ARRAYSIZE]; ...

  1. #1
    Registered User
    Join Date
    Sep 2004
    Posts
    153

    the subscript operator

    Hello,
    So, I didnt know I could do this:
    Code:
    int main()
    {
        const int ARRAYSIZE = 10;
        int myArray[ARRAYSIZE];
        for (int i = 0; i < ARRAYSIZE; i++)
             myArray[i] = i+5;
        cout << myArray << endl;
    
        int* pArray = myArray;
        cout << pArray[0] << endl;
        return 0;
    }
    So then this means that when you use the subscript operator ( [ ] <- I believe subscript op is what it's called...correct me if I'm wrong), so when you use that operator, the function body automatically dereferences the pointer (in this case pArray)?...so now curiously how would the declaration of an array factor into the use of the [] operator? I mean is it a matter of operator overloading? Just something I was thinking about...if you know of any good text to read on the matter that'll work, dont feel likeyou haveta answer this question yourself..I just like to know the inner workings of whats going on, makes the visualization easier in some cases. Chap

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,806
    FYI, in addition to using array indexing with a pointer variable, you can also use pointer like dereferencing and pointer arithmetic on arrays:

    Code:
    const int ARRAYSIZE = 10;
    int myArray[ARRAYSIZE];
    
    ...
    
    cout << *myArray << endl;      // Output 1st element of array (instead of myArray[0])
    cout << *(myArray+4) << endl;  // Output 5th element of array (instead of myArray[4])
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    so now curiously how would the declaration of an array factor into the use of the [] operator? I mean is it a matter of operator overloading?
    I don't think it is operator overloading. This statement:

    int myArray[10];

    creates an int* called myArray and assigns it the address in memory of the first int in the array, with the other ints layed out consecutively in memory after the first int. So, this statement:

    int* pArray = myArray;

    just assigns the address stored in myArray to pArray. They are both pointers, so the subscript operator works the same on both of them.

    There is an important difference between the two pointers, though: an array name is a constant pointer, which means the address stored in the array name cannot be changed.
    Last edited by 7stud; 02-17-2005 at 11:57 AM.

  4. #4
    Registered User
    Join Date
    Sep 2004
    Posts
    153
    thanks for the info guys...and hk_...I comepletely forgot about the other notation! That's good information to hold on...is there a good reason to ever use pointer notiation on arrays or will subscripting generally suffice?

  5. #5
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    Choices always allow you more freedom. For instance, you could do this:
    Code:
    #include<iostream>
    using namespace std;
    
    void f(int* p)
    {
        cout<<*(p + 1)<<endl;
    }
    
    int main()
    {
        int myArray[3]={10, 20, 30};
        int* p = myArray;
        
        f(myArray);
        p++; //moves pointer to the second element of the array;
        f(p);
    
        return 0;
    }
    As an exercise, try writing the same program using only subscripts.
    Last edited by 7stud; 02-17-2005 at 12:53 PM.

  6. #6
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,749
    > creates an int* called myArray
    No it doesn't.

    Almost everything you've said about arrays and pointers there is wrong.
    http://www.eskimo.com/~scs/C-faq/s6.html
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  7. #7
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    Sorry, I'll have to study up on them, then. Thanks. I know when I do this:

    cout<<myArray<<endl;

    I get an address, so that leads me to believe it's a pointer. And, when I do this:

    Code:
    int anotherArray[3] = {1,2,3};
    myArray = anotherArray;
    I get an error saying myArray is not an l-value, so that leads me to believe it's a constant pointer.
    Last edited by 7stud; 02-17-2005 at 01:49 PM.

  8. #8
    Registered User
    Join Date
    Sep 2004
    Posts
    153
    yeah I'm gonna have to agree...in my limited knowledge...I think 7stud's right but I dont know what the hell I'm talking about...

    Hmm...ok...I read question 6.2 on that link of yours...it makes sense...the end result is all the same, it's just how the compiler creates it that's different.
    Last edited by Chaplin27; 02-17-2005 at 01:53 PM. Reason: adding more info to my post...

  9. #9
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    yeah I'm gonna have to agree...in my limited knowledge...I think 7stud's right
    It would be wiser to side with Salem on any issue.

  10. #10
    Registered User
    Join Date
    Sep 2004
    Posts
    153
    lol 7stud...I edited myself...just trying to be supportive hehe

  11. #11
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    I read it too, but I don't get it. It doesn't explain what an array is, it just says it's not a pointer. I find that hard to swallow since when you output the array name it is an address.

    Hopefully, after Salem gets done bloodying my knuckles with a ruler, he/she will explain the details.
    Last edited by 7stud; 02-17-2005 at 02:07 PM.

  12. #12
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    I guess this is the crux of the matter:

    Code:
    int myArray[3]={10, 20, 30};
    
    cout<<myArray<<endl;          //006BFDEC
    int* p = myArray;
    
    cout<<sizeof(myArray)<<endl;  //12
    cout<<sizeof(p)<<endl;        //4
    That says that myArray takes up 12 bytes in memory(4 bytes per element), but p takes up only 4 bytes in memory. The implication is that p is a variable in memory that stores the address of myArray, and that address only takes up 4 bytes. On the other hand, myArray is an object at some location in memory that takes up 12 bytes. Apparently the << operator is defined so that it returns the address of an array(versus it's members or something else), and that makes it appear as if myArray is a pointer when it's actually an object.

    Therefore, the difference between p and myArray is one level of indirection: p is a variable pointing to a location in memory, and myArray is an object at that location.

    However, I'm not sure what benefit making that distinction gains us. It does not appear that an array can be passed by value like other objects. When you pass the array name to a function, the function can change the array permanently--just as if the array name were a pointer:

    Code:
    #include<iostream>
    using namespace std;
    
    void f(int array[])
    {
        array[0] = 14;  //changes first element of the array
    }
    int main()
    {
        int myArray[3]={10, 20, 30};
        cout<<myArray<<endl;
        
        int* p = myArray;
    
        cout<<sizeof(myArray)<<endl;
        cout<<sizeof(p)<<endl;
    
        f(myArray);
        cout<<myArray[0]<<endl;  //14
    
         
        return 0;
    }
    Last edited by 7stud; 02-17-2005 at 04:51 PM.

  13. #13
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    >>Apparently the << operator is defined so that it returns the address of an array
    More likely, there is no << operator defined at all, and the array is implicitly converted to a pointer

    >>I'm not sure what benefit making that distinction gains us.
    One benefit is simply that it is destroyed automatically when it goes out of scope. This prevents accidental memory leaks, semi-accidental memory leaks (i.e. uncaught exception), and saves you a bunch of time and trouble in freeing memory. I suspect, however, that this garbage-cleaning relies on the array being fixed-size - and therefore pointers are necessary to use dynamic arrays. In any case, it's sometimes handy to create an array and then assign a pointer to its address. An example, used for optimization:
    Code:
    const int size = 640 * 480;
    unsigned char theImage[size];
    for(int i = 0; i < size; ++i)
    {
       //do something with theImage[i].. does implicit multiplication operation, very slow!
    }
    //OR
    unsigned char* iterator = theImage;
    unsigned char* end = iterator + size;
    for(; iterator != end; ++iterator)
       //do something with (*iterator).. fast dereference operation!
    Just an example of the sort of fun stuff you can do with pointers, that you can't do with arrays
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Overloading subscript operator for multi-dimensional array.
    By minesweeper in forum C++ Programming
    Replies: 3
    Last Post: 05-12-2011, 11:57 PM
  2. Smart pointer class
    By Elysia in forum C++ Programming
    Replies: 63
    Last Post: 11-03-2007, 08:05 AM
  3. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 03:39 PM
  4. Asigment and subscript operator
    By rusty0412 in forum C++ Programming
    Replies: 4
    Last Post: 01-13-2005, 08:22 AM
  5. operator overloading and dynamic memory program
    By jlmac2001 in forum C++ Programming
    Replies: 3
    Last Post: 04-07-2003, 12:51 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21