Pointers and cstring length

梦想的初衷 提交于 2019-12-23 17:46:06

问题


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;
}

回答1:


With

char name[0];

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 with cin.get(name, 256)):

char name[256];



回答2:


Name is declared as zero length. That is going to be a problem.



来源:https://stackoverflow.com/questions/8539763/pointers-and-cstring-length

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!