-2

I have an array of type 'char' with the last symbol '\0'.

#include<iostream>

void main()
{
    char a[4];

    a[0] = 'r';
    a[1] = 'r';
    a[2] = 'r';
    a[3] = '\0';

     for (int i = 0; i < 6; i++)
     {
         cout << a[i];
     }
     cout << endl;
 }

So, when I try to output more symbols than this array has, It prints random symbols after '\0' symbol.

Output:

rrr ╠╠

My question is: how can I create my array with no symbols after '\0' symbol ?

Yuriy Lisovskiy
  • 501
  • 1
  • 6
  • 13
  • 3
    Possible duplicate of [Accessing an array out of bounds gives no error, why?](http://stackoverflow.com/questions/1239938/accessing-an-array-out-of-bounds-gives-no-error-why) – Algirdas Preidžius Mar 29 '17 at 14:52
  • 3
    You can't. If you go out of bounds you will have *undefined behavior*. End of story. – Some programmer dude Mar 29 '17 at 14:52
  • You can. Write your own class CGreatArray. – KonstantinL Mar 29 '17 at 14:53
  • Use `std::vector a { 'r', 'r', 'r', '\0' };` and access it with `a.at(i)`. – YSC Mar 29 '17 at 14:54
  • But using char array it is impossible ? – Yuriy Lisovskiy Mar 29 '17 at 15:01
  • Raw arrays are directly mapped to memory without any means of access controls. If you do not want that, use classes. – Revolver_Ocelot Mar 29 '17 at 15:07
  • One possible way is to stop at the 0, `for (int i = 0; a[i] != '\0'; i++)` – Bo Persson Mar 29 '17 at 15:07
  • How about using std::string? – Aziuth Mar 29 '17 at 15:17
  • I can't cause I need to create my own class 'String' – Yuriy Lisovskiy Mar 29 '17 at 15:19
  • You already created a null-terminated array (an array with no additional characters after `\0`). The issue is that `a[4]` and `a[5]` aren't actually part of the array; due to how the subscript operator works for C arrays (basically, [it typically translates the index into pointer arithmetic, so that `a[n]` is `*(a + n)`](https://www.le.ac.uk/users/rjm1/cotter/page_59.htm)), they're the next two bytes in memory _after_ the array. The problem was that you tried to access 6 elements of a 4-element array, which means by definition that the last two elements aren't part of the array. – Justin Time - Reinstate Monica Mar 29 '17 at 21:20

1 Answers1

0

First of all, the size ff this array is 4, so when you try to access any element out of range, you read a random memory.

Secondly, '\0' character is a string terminating symbol. You don't need to clear all of the elements followed by it. All of the standard IO functions will not write after '\0'. You can try:

cout << a;

Without any loops.