指针和cstring长度
我在这里设置指针,一个指向名称,另一个指向名称,但获取长度。为什么当我使用cout <<时? strlen(tail);
它一直告诉我长度是3?即使我输入的是 12?
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main()
{
char name[0];
cout << "Please enter your name: ";
cin.getline(name, 256);
cout << "Your name: " << name << endl;
char* head = name;
cout << head[6] << endl;
char* tail = name;
cout << strlen(tail);
return 0;
}
I am setting pointers here one to point to name and one to point to name again but get the lenth. How come when i use cout << strlen(tail);
it keeps telling me the lenth is 3? Even if i enter something that is 12?
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main()
{
char name[0];
cout << "Please enter your name: ";
cin.getline(name, 256);
cout << "Your name: " << name << endl;
char* head = name;
cout << head[6] << endl;
char* tail = name;
cout << strlen(tail);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您
正在分配一个大小为
0
的缓冲区来存储数据。您需要使其足够大以容纳要输入的最长字符串(NUL 终止符加 1),在本例中为 256(因为您正在读取 255 个字符和一个带有cin.get(name ,256):
With
You are allocating a buffer of size
0
in which to store data. You need to make it big enough for the longest string you will enter (plus 1 for the NUL terminator), which would be 256 in this case (because you're reading 255 characters and a NUL withcin.get(name, 256)
):名称被声明为零长度。这将是一个问题。
Name is declared as zero length. That is going to be a problem.