c ++查找char指针的长度

时间:2014-05-07 04:02:39

标签: c++

我正在尝试创建一个从用户输入读入“string”(进入char *)的程序,然后使用cstring,它获取char *指向的长度。根据我的理解,char *是一个指针。对指针的引用将被重定向到它指向的内容。在这种情况下,word应指向4321,当word输出时,它指向的是实际输出的内容。另外,strlen应该读到\ 0,在这种情况下字符串应该是4321 \ 0,那为什么它会出现分段错误?

期望的结果:

Enter a string: 4321
4321
(length of 4321)

程序:

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    char *word;
    int len;

    cout << "Enter a string: ";
    cin >> word;

    len = strlen(word); //why does this cause a segmentation fault?

    cout << word << endl;
    cout << len << endl;

    return 0;
}

2 个答案:

答案 0 :(得分:4)

你需要

char word [256] ; // or something

更好的

std::string word ;


cout << word.length () ;

答案 1 :(得分:1)

在你的代码&#34; word&#34;只是一个指针。如果您想直接在指针中写入内容,首先必须为其分配有效的内存地址。如果对你来说并不重要,那么#34; word&#34;是指针,然后char数组就足够了。

相关问题