0

Could you please help me why this code is not printing the char array of '*' chars as expected?

int n = 10;
char *cs = (char*) calloc(n + 1, sizeof(char));
for (int i = 0; i < n; i++) {
    cs[i] = '*';
}
cout << cs << endl;

Googled around a lot, but didn't find the same problem anywhere..

Thanks!

9
  • 3
    I doesn't reproduce if I complete the code in the obvious (at least for me) way. Please give the full code. Nov 10, 2012 at 19:42
  • @H2CO3 The terminating zero is there because of calloc. Nov 10, 2012 at 19:45
  • calloc() should have done this. @H2CO3
    – alk
    Nov 10, 2012 at 19:45
  • This works like a charm, take a look: link to ideone. Nov 10, 2012 at 19:45
  • code is running fine ideone.com/49GA6P Nov 10, 2012 at 19:46

1 Answer 1

1

I have written the same code in the studio and for me its working fine. Giving * as output.

int main()
{
    int n=10;
    char *cs = (char*) calloc(n+1, sizeof(char));
    for (int i=0; i<n; i++) {
        cs[i] = '*';
    }
    cout << cs << endl;
    return 0;
}
1
  • Yep, now it's OK. Eclipse worked strangely for me somehow.. Thanks! Nov 10, 2012 at 19:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.