-3
#include <iostream>
#include <string>
#include <cmath>
#include <bits/stdc++.h>
using namespace std;
int main()
{

    char x[3]={'a','b','c'} , y[3]={'e','f','j'};

// first loop here it prints the elements of the targeted array with the elements of the other array in each loop .

    for (int i = 0; i < 20 ;i++)
    {
        cout << y ;
    }
    cout << "\n\n" ;

//second loop prints the elements of targeted array with extra variable character each loop .

    for (int i = 0; i < 20 ;i++)
    {
        cout << x ;
    }

    return (0) ;
}
sehes
  • 11
  • 2
  • `cout << y` exhibits undefined behavior, as `y` is not NUL-terminated. So does `cout << x`. Both expressions call `operator< – Igor Tandetnik Mar 28 '18 at 04:11
  • [Possible duplicate](https://stackoverflow.com/questions/46507641/printing-char-arrays-c). – user202729 Mar 28 '18 at 04:23
  • Be careful with `using namespace std;` ([Why is “using namespace std” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice)) and don't use `#include ` ([Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h)). Definitely do not use them together; it turns your code into a minefield. – user4581301 Mar 28 '18 at 04:40

3 Answers3

0

To print a character using cout or printf null terminated string is required. You have declared the character array as string which is not null terminated.

Change the line with null terminated char, then it will print properly.

char x[4]={'a','b','c','\0'} , y[4]={'e','f','j','\0'};
I. Ahmed
  • 2,287
  • 1
  • 9
  • 28
0

If you used char x[4] = "abc"; (note number of elements in the array) then

After any necessary concatenation, in translation phase 7 (5.2), ’\0’ is appended to every string literal so that programs that scan a string can find its end.

and so length of x would be 4:

The size of a narrow string literal is the total number of escape sequences and other characters, plus at least one for the multibyte encoding of each universal - character - name, plus one for the terminating ’\0’.

But if you want to use an array, you need to provide '\0' explicitly:

char x[4]={'a','b','c','\0'} , y[4]={'e','f','j','\0'};

See [lex.string] for more info.

Yola
  • 16,575
  • 11
  • 57
  • 92
0

Most of the or all api looks for the null terminated character when the prints the char array. So '\0' must be added at the end of char array. Which will effectively increase the array size by 1.

So the correct program will be like below.

#include <iostream>
#include <string>
#include <cmath>
#include <bits/stdc++.h>
using namespace std;

int main()
{

    char x[4]={'a','b','c', '\0'} , y[4]={'e','f','j', '\0'};

    for (int i = 0; i < 20 ;i++)
    {
        cout << y <<endl;
    }
    cout << "\n\n" ;

    for (int i = 0; i < 20 ;i++)
    {
        cout << x <<endl;
    }
    return (0) ;
}
Swapnil
  • 259
  • 2
  • 18