Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/145.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/magento/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c++;查找字符指针的长度_C++ - Fatal编程技术网

C++ c++;查找字符指针的长度

C++ c++;查找字符指针的长度,c++,C++,我试图制作一个程序,从用户输入中读入一个“字符串”(转换成一个char*),然后使用cstring,它得到char*指向的长度。据我所知,char*是一个指针。对指针的引用将重定向到它所指向的对象。在本例中,word应该指向4321,当word获得输出时,它指向的是实际获得输出的内容。另外,strlen应该一直读到\0,在这种情况下字符串应该是4321\0,那么为什么它会出现分段错误呢 预期结果: Enter a string: 4321 4321 (length of 4321) 节目: #

我试图制作一个程序,从用户输入中读入一个“字符串”(转换成一个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;
}
#包括
#包括
使用名称空间std;
int main()
{
字符*字;
内伦;
cout>单词;
len=strlen(word);//为什么这会导致分段错误?
你需要什么

char word [256] ; // or something
更好

std::string word ;


cout << word.length () ;
std::字符串字;

cout在您的代码中,“word”只是一个指针。如果您想将某些内容直接写入指针,首先必须为其分配一个有效的内存地址。如果“word”是指针对您来说并不重要,那么一个字符数组就足够了。

但是“char*word”和“char-word[256]”除了后者被限制为255个元素(不包括“\0”)之外,应该是相同的。char word[256];创建指向包含256个字节的缓冲区的指针。char*word;创建指向任何内容的指针(直到分配为止)。“cin>>word;”不分配吗?@user2871213不,不分配。这里不是学习教程的地方。@user3344003,
char-word[256]
创建一个256字节的数组,它不会创建一个点。您没有初始化
word
,因此它包含指向内存中某个随机位置的垃圾。您试图读取该随机位置。操作系统明智地告诉您不能这样做。将来您可能需要等待一段时间才能接受答案。