Character Arrays

Hello cplusplus forums.
Newb here.

I'm having problems with character arrays.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <conio.h>
using namespace std;

int main()
{
	char array1[15], array2[15], array3[5], again = 'y';
	
	while (again == 'y')
	{
		system("cls");
		cout << "Enter first word (15 characters): ";
		cin >> array1;
		cout << "Enter second word (15 characters): ";
		cin >> array2;
		cout << "Enter third word (5 characters): ";
		cin >> array3;
	
		cout << array1 << " " << array2 << " " << array3;
		getch();
		cout << "\n\nAgain? ";
		cin >> again;
	}
	
	return 0;
}


Enter the first word (15 characters): Banana
Enter the second word (15 characters): Marshall
Enter the third word (5 characters): ui897
Banana  ui897



Enter the first word (15 characters): Banana
Enter the second word (15 characters): Marshall
Enter the third word (5 characters): n7
Banana Marshall n7


If you input the max amount of characters in a character array, its like the one entered before that one gets erased from memory. Can anybody explain this?
Last edited on
A C-string is an array of char, in which the end of the string is marked with a zero.

array3 can take 5 char values - one of these must be the terminating zero. If you enter ui897, then the terminating zero will go immediately after the fifth element. You will be writing over some other data.

In this case, I expect that the data being written over is the first char of array2, so that when time comes to print out array2, it begins with a zero (ie. begins with the character that indicates end-of-string).

The following code will confirm this for you:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>

using namespace std;

int main()
{
	char array1[15], array2[15], array3[5], again = 'y';
	
	while (again == 'y')
	{
	
		cout << "Enter first word (15 characters): ";
		cin >> array1;
		cout << "Enter second word (15 characters): ";
		cin >> array2;
		cout << "Enter third word (5 characters): ";
		cin >> array3;
	
		cout << array1 << " " << array2 << " " << array3 <<endl;
                cout << "Address of array2[0] is " << (int*)&array2[0] << endl;
                cout << "Address of array3[5] is " << (int*)&array3[5] << endl; // array3[5] is off the end of the array


	
		cout << "\n\nAgain? ";
		cin >> again;
	}
	
	return 0;
}

Last edited on
I think I understand. Thanks for the quick reply.
Topic archived. No new replies allowed.