0

I have a question regarding pointers to custom classes. Consider the below C++ fragment:

#include <iostream>
#include <vector>

class custom {
    public :
        int first;
        
    custom(int x)
    { 
        first = x;
    }
};

int main() {
    
    custom c1(1);
    custom c2(2);
    custom c3(3);
    custom c4(4);
    
    std::vector<custom> c;
    c.push_back(c1);
    c.push_back(c2);
    c.push_back(c3);
    c.push_back(c4);
    
    // How can this work ?
    // cp has size 2 ?
    custom* cp[2]; 

    for(int i = 0; i <= 2; ++i) 
    {
        cp[i] = &c.at(i);
        std::cout << (*cp[i]).first << std::endl;
    }
    return 0;
}

I create a class called custom and create 4 class objects. Next I create a pointer to the class of size 2 and assign it the address of the of the vector object.

If I print the output I would get :

1
2
3

How can a pointer of size 2 access the last index ? Is there some custom resizing going on under the hood ?

If I instead change the loop to go upto i <= 3, it can access the last element but throws :

1
2
3
4
*** stack smashing detected ***: terminated
Aborted

My question is why doesn't the pointer throw an index out of range error and how can it access these elements ?

  • this does not "work". `cp[i] = &c.at(i);` is accessing `cp` out of bounds in the last iteration. Your code has undefined behavior. Anything can happen – 463035818_is_not_an_ai Oct 20 '22 at 18:01
  • don't confuse pointers with arrays. Pointers are not arrays and arrays are not pointers. `custom* cp[2];` declares `cp` to be an array of size 2. The elements of the array are poitners to `custom`. – 463035818_is_not_an_ai Oct 20 '22 at 18:02

0 Answers0