Reputation: 2810
#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.
Upvotes: 0
Views: 98
Reputation: 63501
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};
Upvotes: 4