Array in c++

Why the array not created according to the array size?

these are my coding:

#include <iostream>
#include <string>
#include <string.h>

using namespace std;
int main()
{

int l =9;
char my[l];
int a = 0;


for(int a=0; a<(l); a++)
{

if(a%2 == 0)
{
my[a] = 'R';
}
else
{
my[a] = ' ';
}


}

/*while(a<(l-1))
{

my[a] = 'r';
/*if(a%2 == 0)
{
my[a] = 'R';
}
else
{
my[a] = ' ';
}
a++;
}*/

cout<<my<<endl;
//int p = strlen(my);
//cout<<p<<endl<<endl;
}


I have try to compile it and the result is as below:

R R R R R�

i expected to get this result:

R R R R R
You didn't write a terminating zero, you just filled the array with spaces and 'R's all the way to the end.
Just add my[l - 1] = 0 somewhere after the for.
thanks for the reply. i had tried and its work, but what is the function of terminating zero? does it affect if the size of the array change to smaller or larger size?
An "old" C-Style Array always terminates with '/0' that tells to the compiler that the allocated space in memory pointing to them is terminated. It is the raw version of vector<int> v{1,2,3}; v.size(); . In C++ is preferable to use vectors because are more "smart" than arrays, they know "their size" and are standardized. Hope this helps :)
Last edited on
Thanks for the reply. its really help.
You're welcome!
Topic archived. No new replies allowed.