explain fragment of code


Im having trouble understanding this code, i see why the first printf outputs 28 seeing as there are 28 characters in the string. but i am confused on the second printf, im assuming it prints 23 because it excludes the space characters in the string but how does the code break down? where does the (&strlen[5]) come into play...thanks in advance

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

main()
{
	
	char str[] = "My Brother was an only child";
	printf("%d\n",strlen(str));
	printf("%d",strlen(&str[5]));
	return EXIT_SUCCESS;
}
Last edited on
closed account (E0p9LyTq)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
   char str[] = "My Brother was an only child";

   printf("%d\n",strlen(str));
   printf("%d\n",strlen(&str[5]));

   printf("%s\n", str);
   printf("%s\n", &str[5]);
   
   return 0;
}

28
23
My Brother was an only child
other was an only child

PLEASE learn to use code tags, it makes it easier to read and comment on your source code.

HINT: you can edit your post and add code tags.

http://www.cplusplus.com/articles/jEywvCM9/
C strings have a hidden zero character that indicates end of string.
so what this does...
the second printf takes a character pointer at the 6th location (0,1,2,3,4,5th) or
My_Bro <---- the pointer is on this 'o' character
012345
and prints starting from there until end of the string.
line 10 counts from the new pointer until the zero end of string marker.

or, in summary, &str[5] tells the machine to jump to the 'o' in brother and start there as if that were the whole string.

Last edited on
Topic archived. No new replies allowed.