-1

I've been reviewing my C++ lately. But I am running into a puzzle about printing a char array. The code is below:

int n = 5;
char *array1 = new char[n];
for (unsigned int i = 0; i < n - 1; i++)
    array1[i] = (char)i;
cout << array1 << endl;
cout << array1[3] << endl;
cout << *array1 << endl;

None of the three cout lines works. Could anyone tell me why?

Holie Chen
  • 13
  • 4

2 Answers2

1

array1[0] == 0. cout << array1 interprets array1 as a pointer to a NUL-terminated string, and since the very first character is in fact NUL, the string is empty.

cout << array1[3] does print a character with ASCII code 3. It's a non-printable character, not visible to a naked eye. Not sure what output you expected to see there.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
0

As a separate answer, it seems you're trying to get a string which has the following : array = "1234....(n-1)"

Try :

for (int i = 0; i<(n-1); i++)
    array1[i] = (char)i - '0';
Shivansh Jagga
  • 1,541
  • 1
  • 15
  • 24
  • Should be '+' I suppose? – Holie Chen Jun 27 '17 at 14:30
  • If its ' - ' ,this is what it does : `(ASCII value of n) - (ASCII value of 0) = n` . So if its the number 0, it becomes `(ascii of 0) - (ascii of 0) =0` itself. Please up vote incase I helped ^_^ – Shivansh Jagga Jun 27 '17 at 14:33
  • 1
    I don't think so. Because (char)i means "character with ascii code of i" but not "ascii code of character 'i' ". So it should be '+'. – Holie Chen Jun 27 '17 at 14:47