Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ pointer to char arithmetic

If I add 1 to a pointer, the actual value added will be the size of the type that the pointer points to right? For example:

int* num[5];
cout << *num << ", " << *(num + 2) << endl; 

This will print the value stored at num[1] and at num[2], so num + 2 is actually num + 2*sizeof(int) if I'm not wrong.

Now, if I initialize an array of pointers to char to string literals, like this one:

char* ch[5] = 
{
     "Hi",
     "There",
     "I,m a string literal"
};

This can be done because a string literal like "hi" represents the address of its first character, in this case 'h'. Now my question is how can I write something like:

cout << *(ch + 2);

and get "I,m a string literal" as the output? Since the pointer points to char, shouldn't adding 2 to the pointer actually be (ch + 2*sizeof(char)) ? giving me the output 'There' ?

Does it have something to do with cout? Does cout search the memory of the pointed to values to see if it finds '\0's recognizing the contents of the pointed to values as strings and then modifying pointer arithmetic? But then adding 1 to a pointer to char pointing to strings would mean adding different number of bytes (instead of the size of a char) everytime, since a string can be any size. Or am I totally wrong? I'm sorry I am new to C++, and programming in gerenal.

like image 539
Lucas Mezalira Avatar asked Nov 21 '25 15:11

Lucas Mezalira


1 Answers

The array isn't storing chars, it's storing char *s. Hence saying ch + 2 will be equivalent to ch + 2*sizeof(char *). You then dereference that, which is pointing to "I'm a string literal".

Your initial example shows the confusion:

int* num[5];
cout << *num << ", " << *(num + 2) << endl; 

This is an array of pointers-to-int. Hence, *(num + 2) will be *(num + 2*sizeof(int *)), not 2*sizeof(int). Let's demonstrate this with a small program:

#include <iostream>

int main()
{
    int *num[3];
    int x, y, z;
    x = 1;
    y = 2;
    z = 3;

    num[0] = &x;
    num[1] = &y;
    num[2] = &z;

    std::cout << *(num + 2) << "\n";
}

This will print out a memory address (like 0x22ff28) because it is holding pointers, not values.

In C and C++, arrays and pointers are very similar (many books claim they are exactly the same. This is not -quite- true, but it is true in a lot of situations).

Your first example should be int num[5]. Then *(num + 2) (which is equivalent to num[2]) will be equivalent to *(num + 2*sizeof(int). Hopefully this clears up your confusion somewhat.

like image 123
Yuushi Avatar answered Nov 24 '25 06:11

Yuushi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!