You are confusing several things.
strtok takes in arguments (char*, const char*)....name is an array and hence a pointer to its first element...
name is an array, and it's not a pointer to its first element. An array decays in a pointer to its first argument in several contexts, but in principle it's a completely different thing. You notice this e.g. when you apply the sizeof operator on a pointer and on an array: on an array you get the array size (i.e. the cumulative size of its elements), on a pointer you get the size of a pointer (which is fixed).
but if we made a declaration like string name="avinash" and passed name as argument
then the prog doesnt work but it should because name of string is a pointer to its first character...
If you make a declaration like
string name="avinash";
you're are saying a completely different thing; string here is not a C-string (i.e. a char[]), but the C++ std::string type, which is a class that manages a dynamic string; those two things are completely different.
If you want to obtain a constant C-string (const char *) from a std::string you have to use it's c_str() method. Still, you can't use the pointer obtained in this way with strtok, since c_str() returns a pointer to a const C-string, i.e. it cannot be modified. Notice that strtok is not intended to work with C++ strings, since it's part of the legacy C library.
also if we write const string n = "n"; and pass it as second argument it doesnt work...this was my first problem...
This doesn't work for the exact same motivation, but in this case you can simply use the c_str() method, since the second argument of strtok is a const char *.
now also the sizeof(name) output is 8 but it should be 4 as avinash has been tokenised..
sizeof returns the "static" size of its operand (i.e. how much memory is allocated for it), it knows nothing about the content of name. To get the length of a C-string you have to use the strlen function; for C++ std::string just use its size() method.
sizeof(name)should change. Note thatsizeofis not the same asstrlen...