Why does this code output the following?

Im not sure why this code prints out "C". I did learn about strlen but its different here and im confused. Any help is appreciated and i want an explanation on why it outputs C so i know what is going on. Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream>
#include <cstring>
using namespace std;
void func(const char* s, char& c)
{
c = s[strlen(s) / 2];
}
int main()
{
char str[] = "ABCDE";
char ch = str[1];
func(str, ch);
cout << ch << endl;
return 0;
}
If you print out strlen(s) in the function it'll be more clear.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
#include <cstring>
using namespace std;
void func(const char* s, char& c)
{
	cout << strlen(s);
	c = s[strlen(s) / 2];
	
}
int main()
{
	char str[] = "ABCDE";
	char ch = str[1];
	func(str, ch);
	cout << ch << endl;
	
	return 0;
}


strlen(s) is equal to 5.
5 divided by 2 is 2.5, but since it's integer division it is rounded down to 2.
c becomes equal to s[2];
and s[2] is = C (you'll know about this if you know how arrays work)
Last edited on
Thanks so much. By the way, to count strlen , you start at 0 right? Just to makes sure
you start at 0 right? Just to makes sure

I'm not 100% what you mean. I believe you start at 1. For example -

strlen of "just testing" would give you 12, because it's 12 characters.
http://www.cplusplus.com/reference/cstring/strlen/
Last edited on
Oh i see. i was confused since s[2] would equal to "B" as stated in "ABCDE" but i think i know where it is . s[2] = c so it outputs C.
Yes, arrays start at 0. So if you had an array like this - int arr[5]
You would access it's values through arr[0-4]
http://www.cplusplus.com/doc/tutorial/arrays/
ok i see thanks haha ty
If you want n easy way to remember why indexes start at zero, just say

The first element in an array is zero past the beginning.
Topic archived. No new replies allowed.