I have attached the program link in which I have commented down my doubt . Can you please help me out?https://ide.codingblocks.com/s/442647
Tokenization using strtok()
@sarthak_singhal in this you are already storing like this:
char *ptr = strtok(s," ");
and if you will do *ptr again then you are getting T as because it is storing the addredd of the first letter of the string.
That is my query that in pointers if we take int * ptr = &a; so cout<<*ptr will give value of a and cout<<ptr will give the address of a but in this case ptr is giving the string not address ??
@sarthak_singhal check this:
this will help you build you concept with strings:
In the above example, since p stores the address of name[0], therefore the value of *p equals the value of name[0] i.e., ‘S’. So in while loop, the first character gets printed and p++ increases the value of p by 1 so that now p+1 points to name[1]. This continues until the pointer reaches the end of the string i.e., before *p becomes equal to ‘\0’.
In the program that you have given you have used *p to access the value of array . That’s my doubt that we have used char * a = strtok(s," ") but to access value we are using only a not *a.
@sarthak_singhal you can read about the return type of the strtok in this:
http://www.cplusplus.com/reference/cstring/strtok/
its because the nature of the strtok:
If a token is found, a pointer to the beginning of the token.
Otherwise, a null pointer .
A null pointer is always returned when the end of the string (i.e., a null character) is reached in the string being scanned.
ok so the reason why u r getting string in place of address is becuase the pointer type is char .
compiler treats char * type pointers differentely .
whenerver u will try to print the pointer address it will start printing its content till it found \0 (only in the case of char * pointer).
also there is no relation of this behaviour with strtok function.
here is the proof.
@aman212yadav is right. That is the correct reason why you see the string printing instead of its address. If you wish to print the address instead for some reason, you can do that by typecasting as well.
cout << (void *) ptr;
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.