Array pointer arithmetics

Hello all,

I have a question regarding array pointer arithmetics.

If I execute the following code:

1
2
3
4
5
6
7
8
9
    char* l1 = new char[3];
    char* l2 = new char[4]; //size 4 this time
    
    l1[0] = 'a';
    l1[1] = 'b';
    l1[2] = 'c';
    
    l2 = l1 + 1; //reference
    cout<<l2;


I will get the following as output:
 
bc


I don't understand what happens at this line of the code:
 
 l2 = l1 + 1; //reference 


Does the l2 array still has a size of 4 elements or is this smaller because I did l1 + 1?

Thanks.
First of all the code has undefined behavior. It is not necessary that you will get exactly
bc
because this sequence of characters is not terminated by zero character.
As for the pointer arithmetic. If l1 points to the first character of character sequence 'a', 'b', 'c', that is to 'a', then l1 + 1 will point to the next character in the sequence that is to 'b'.
So after statement

l2 = l1 + 1;

the value of l2 will be equal the value of l1 + 1. Address of the character array allocated as new char[4]; will be lost. No pointer will store the address.
Last edited on
Topic archived. No new replies allowed.