C++ - Print contents of array

Jun 11, 2020 at 7:31pm
Hello,

Why is extra content printed on the first array?
But the second array works correctly.

Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream>
using namespace std;

int main()
{
	//char secondString[] = { 'D', 'A','N','I' }; // it has a problem abd print other things
	char secondString[] = { "DANI" }; // it work
	
	for (char * cp = secondString; * cp ; cp++)
	{
		cout << (*cp);
	}
	return 0;
}
Jun 11, 2020 at 7:33pm
string literals like "DANI" automatically have a null terminator on them.
That is, "DANI" becomes an array of size 5, { 'D', 'A', 'N', 'I', '\0' }.

An array of individual characters { 'A', 'B', 'C' } has no null terminator, so the for loop will go out of bounds (undefined behavior).
Last edited on Jun 11, 2020 at 7:34pm
Topic archived. No new replies allowed.