int main()
{
char name[]="avinash";
const char* nameano="a";
strtok(name,"n");
cout<<"the size of name is"<< sizeof(name);
cout<< name;
}
Run Code Online (Sandbox Code Playgroud)
strtok takes in arguments (char*, const char*); name is an array, and hence a pointer to its first element. But if we make a declaration like
string name="avinash";
Run Code Online (Sandbox Code Playgroud)
and pass name as first argument to strtok, then the program doesn't work, but it should, because name, a string, is a pointer to its first character.
Also, if we write
const string n = "n";
Run Code Online (Sandbox Code Playgroud)
and pass it as second argument it doesn't work; this was my first problem.
Now also the sizeof(name) output is 8, but it should be 4, as avinash has been tokenized. Why does this happen?
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";
Run Code Online (Sandbox Code Playgroud)
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...
这不适用于完全相同的动机,但在这种情况下,您可以简单地使用该c_str()方法,因为 的第二个参数strtok是 a 。const char *
现在 sizeof(name) 输出也是 8,但它应该是 4,因为 avinash 已被标记化..
sizeof返回其操作数的“静态”大小(即为其分配了多少内存),它对name. 要获得 C 字符串的长度,您必须使用该strlen函数;对于 C++,std::string只需使用它的size()方法。
| 归档时间: |
|
| 查看次数: |
2755 次 |
| 最近记录: |