Concatenate an Array Into Another Array

Hi, I'm not sure if anyone had ask this question before, but I can't find an answer to this question on Google.

So I have an array and I want to concatenate it into another array, but I have a question about the size of the array. Here is my code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <cstdio>
using namespace std;

int main(){
    char array1[4];
    char array2[6];
    int interger = -23;

    // Write formatted data (integer)to string (array1)
    sprintf(array1 , "%i" , integer);

    // Concatenate array1 into array2
    strcat(array2, array1);

    cout << array2;
    
    return 0;
}


With this code the output is the way that I wanted:

-23


But if I change the size of array2 from 6 to something such as 23 so the array become this:
array2[23];

I get this:

└☼q-23


I don't know why when I change the size of array2 into 23 I get some junk before the actual content of the array. Am I missing something here? And am I using the strcat() function correctly?

Thank you for looking at my question.

PS. I use DevShed to compile this program.
Last edited on
array1 and array2 both contain junk so using strcat on them isn't useful. You need use null-terminated character arrays in order for strcat to work correctly.
I see, thank you firedraco. After I initiate both arrays with null-terminated character, it work no matter what size the arrays are.
The final array needs to be large enough to hold the result. There is no runtime check to do this for you, so you have to take care of this yourself. It's called a buffer overrun.
http://en.wikipedia.org/wiki/Buffer_overrun
Thank you kbw, I will keep that in mind when declaring the size of the arrays.
Topic archived. No new replies allowed.