0
#include <iostream>

int main() {
    char* chars = new char[4];
    for(int i = 0; i < 4; ++i)
    {
        chars[i] = 'a';
    }
    std::cout << chars;
    return 0;
}

That chunk of code works correctly. stdout says

aaaa

However, changing

chars[i] = 'a';

to

*chars++ = 'a';

or

*(chars++) = 'a';

make stdout empty with nothing in stderr. What's going on? I thought the [] was just syntactic sugar for *pointer.

3
  • 1
    Should be (*chars)++. Commented Oct 22, 2013 at 22:45
  • 1
    It would be most equivalent to *(chars + i), but the code has undefined behaviour either way. Commented Oct 22, 2013 at 22:46
  • changing it to (*chars)++ gives me an error lvalue "required as left operand of assignment" Commented Oct 22, 2013 at 22:52

1 Answer 1

4

The problem is that by iterating through chars using *chars++ = 'a' you modify the pointer. When you finally output the string, it is pointing to the character just past the end of the string.

Perhaps you were trying to do something like this:

for( char *p = chars, *end = chars + 4; p != end; )
{
    *p++ = 'a';
}

But this is ugly. The first way (chars[i]) was better. In either case, your array is not large enough to hold a 4-character string because you need a null-terminator.

char *chars = new char[5];
char *p = chars;
for( int i = 0; i < 4; i++ ) *p++ = 'a';
*p = '\0';                                    // null-terminate the string
cout << chars;
delete [] chars;

Note that there's not much use in dynamic allocation in your case. Why not just declare chars on the stack? Also, initialising it with all zeroes is not a bad practice:

char chars[5] = {0};
Sign up to request clarification or add additional context in comments.

1 Comment

All I read was "initialising it with all zeroes is not a bad practice." +1 for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.