指针和字符串长度 [英] Pointers and cstring length

查看:122
本文介绍了指针和字符串长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里将指针设置为一个指向名称,另一个设置为指向名称,但是得到的是长度.为什么当我使用cout << strlen(tail);时,它总是告诉我长度是3?即使我输入的是12?

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

推荐答案

使用

char name[0];

您正在分配大小为0的缓冲区,用于存储数据.您需要使其足够大以容纳您要输入的最长字符串(对于NUL终止符加1),在这种情况下为256(因为您正在读取255个字符和一个带cin.get(name, 256)的NUL):

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

这篇关于指针和字符串长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆