strcpy() changes return array

Hi all,
I don't understand line 29:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
template <typename T, int nSize> // nSize is the expression parameter 
class Buffer { 
private:     // The expression parameter controls the size of the array     
    T m_atBuffer[nSize];   
public:     
    T* GetBuffer() { return m_atBuffer; }       
    T& operator[](int nIndex) {         
        return m_atBuffer[nIndex];
    } 
};   

int main() {     
    // declare an integer buffer with room for 12 chars     
    Buffer<int, 12> cIntBuffer;
       
    // Fill it up in order, then print it backwards     
    for (int nCount=0; nCount < 12; nCount++)         
        cIntBuffer[nCount] = nCount;       

    for (int nCount=11; nCount >= 0; nCount--)         
        std::cout << cIntBuffer[nCount] << " ";
     
    std::cout << std::endl;
       
    // declare a char buffer with room for 31 chars     
    Buffer<char, 31> cCharBuffer;       

    // strcpy a string into the buffer and print it     
    strcpy(cCharBuffer.GetBuffer(), "Hello there!");     
    std::cout << cCharBuffer.GetBuffer() << std::endl;       

    return 0; 
}


The return value of GetBuffer() is modified, and this return value is the buffer itself. Is it really possible to change variables in this way?
The return value of GetBuffer() is modified, and this return value is the buffer itself.

The return value is a pointer to an array.

Is it really possible to change variables in this way?

Yes. If you have a pointer to a variable, you can use that pointer to read and set the variable's value (unless it is a const, of course).
The return value of GetBuffer() is modified
No it isn't.

and this return value is the buffer itself
The return value of GetBuffer() is a pointer to the first element in the array m_atBuffer.

Is it really possible to change variables in this way?
strcpy receives a pointer and it is possible to change the data that a pointer points to. If you don't want to allow the data to be modified you should change GetBuffer() to return a const T*.
I see. And now I understand SDL_PollEvent( &event ) as well. Thanks!
Topic archived. No new replies allowed.