Char array wierd characters

CODE:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

using namespace std;

void testfunc(char* outStr)
{
  //char str[10];
  for(int i=0; i < 4; i++)
  {
    outStr[i] = 'O';
  }
}

int main()
{
    char test[4];
    testfunc(test);
    cout << test;
    int iInt=3;
    test[iInt] = 'P';
    cout << " " << test;
    return 0;
}



Whenever I run this program I get:OOOO OOOP❤
Why do I get the heart? Thx in advance.
Last edited on
Because last symbol in char array always should be \0.
http://en.wikipedia.org/wiki/Null-terminated_string
So I tryed editing like this:
1
2
3
4
5
6
7
8
9
void testfunc(char* outStr)
{
  //char str[10];
  for(int i=0; i < 4; i++)
  {
    outStr[i] = 'O';
  }
  outStr[4]='\0';
}

And I still get the heart, but when I do this:
1
2
3
4
5
6
7
8
9
10
int main()
{
    char test[4];
    testfunc(test);
    cout << test;
    int iInt=3;
    test[iInt] = 'P';
    cout << "          " << test;
    return 0;
}

It's fine.

Please someone tell me, what am I doing wrong?
Last edited on
1
2
    char test[5];    // allow one extra character for the null terminator
    test[4] = '\0';  // and make sure it is set to null. 
Last edited on
thx got it working, btw sorry I took so long to reply
Topic archived. No new replies allowed.