Shiba Tatsuiya
Shiba Tatsuiya

Reputation: 43

How to access array of characters in different ways

I've a function using pointer arithmetic to print out all character inside char*:

void printCharArray(char* c,int n)
{
    for (char*p=c+n-1; n; n--) 
        cout << *p--;
}

The above code works but I want to try another way which is not working:

void printCharArray(char* c,int n)
{
    char *p = &c [n - 1];
    for (int i = 0; i < n; i++)
        cout << *--p;
}

The strange behavior is that if I change char *p = &c [n - 1]; to char *p = &c [n]; then it's working but I expect &c [n - 1] equal to the last character inside the char array but not &c[n]?

Upvotes: 0

Views: 32

Answers (1)

Caninonos
Caninonos

Reputation: 1234

--p; is equivalent to p = p - 1; p;
p--; is equivalent to auto tmp = p; p = p - 1; tmp

in other words

void printCharArray(char* c,int n)
{
    for (char*p=c+n-1; n; n--) 
        cout << *p--;
}

this will display *p, *(p - 1), ..., *(p - n)

void printCharArray(char* c,int n)
{
    char *p = &c [n - 1];
    for (int i = 0; i < n; i++)
        cout << *--p;
}

this will display *(p - 1), *(p - 2), ..., *(p - (n+1))

Upvotes: 1

Related Questions