Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointer arithmetic on arrays

When I run the code below my output is not what I expect.

My way of understanding it is that ptr points to the address of the first element of the Str array. I think ptr + 5 should lead to the + 5th element which is f. So the output should only display f and not both fg.

Why is it showing fg? Does it have to do with how cout displays an array?

#include <iostream>
using namespace std;

int main()
{
    char *ptr;
    char Str[] = "abcdefg";

    ptr = Str;
    ptr += 5;

    cout << ptr;

    return 0;
}

Expected output: f

Actual output: fg

like image 499
kat Avatar asked Feb 09 '23 00:02

kat


1 Answers

When you declare:

char Str[] = "abcdefg"

The string abcdefg is stored implicitly with an extra character \0 which marks the end of the string.

So, when you cout a char* the output will be all the characters stored where the char * points and all the characters stored in consecutive memory locations after the char* until a \0 character is encountered at one of the memory locations! Since, \0 character is after g in your example hence 2 characters are printed.

In case you only want to print the current character, you shall do this ::

cout << *ptr;
like image 110
user007 Avatar answered Feb 16 '23 03:02

user007