1 c++ arrays string pointers sizeof
我试图获得由stdin填充的数组的大小:
char *myArray;
cin >> myArray
cout << sizeof(myArray);
Run Code Online (Sandbox Code Playgroud)
当我输入长度大于4的字符串时,返回4,例如"40905898"
我哪里错了?
Meh*_*ari 11
sizeof
operator静态地计算你传递给它的东西的大小.A char*
是一个指针,根据机器架构有一个特定的大小(32位系统上4个字节,64位机器上8个字节).为了完成你正在尝试做的,我建议你使用string
,你可以通过添加使用类型#include <string>
连同using namespace std;
您的源文件.
string line;
cin >> line;
cout << line.length() << endl;
Run Code Online (Sandbox Code Playgroud)
它不易出错,更易于使用.
顺便说一下,你试图做的事情真的很危险.事实上,当你使用时cin >> myArray
,你应该已经分配了一些myArray
你还没有完成的内存.这将导致内存损坏,这可能会导致程序崩溃并可能使其缓冲溢出攻击.
C++中的一个简单数组不知道它的大小.您可以使用sizeof
只有当数组是静态分配的,并且您使用sizeof
的阵列本身,而不是另一个指针指向它,例如你可能希望这不会工作:
int x[5];
int *a = &x[0];
// a[i] is now the same as x[i] but:
cout << sizeof(x) << endl; // prints 20, assuming int is 32 bits long
cout << sizeof(a) << endl; // prints 4, assuming a pointer is 32 bits long
Run Code Online (Sandbox Code Playgroud)
请注意,数组的总大小打印在第一行,而不是元素计数.您可以使用sizeof(x)/sizeof(*x)
查找静态数组中的元素计数.对于使用动态分配的数组,这是不可能的new
.事实上,C++数组非常容易出错,在使用它们时你应该格外小心,vector
而且string
在大多数情况下你最好使用它.
归档时间: |
|
查看次数: |
3762 次 |
最近记录: |