C 指针字符



我是C 的新手,现在我正在学习指针。我正在尝试理解这个程序:

#include <iostream>
int main() {
    char *text = "hello world";
    int i = 0;
    while (*text) {
        i++;
        text++;
    }
    printf("Char num of <%s> = %d", text, i);
}

它输出:

Char num of <> = 11

但是为什么不这样做:

Char num of <hello world> = 11

随着您的增加text,直到指向'',字符串打印为空。

您在打印出来之前更改了text的值:

#include <iostream>
int main() {
    // text starts pointing at the beginnin of "hello world"
    char *text = "hello world"; // this should be const char*
    int i = 0;
    while (*text) {
        i++;
         // text moves forward one character each time in the loop
        text++;
    }
    // now text is pointing to the end of the "hello world" text so nothing to print
    printf("Char num of <%s> = %d", text, i); 
}

炭指针的值(例如text)是它指向的字符的位置。如果将text增加一个(使用text++),则指向下一个字符的位置。

不确定为什么要使用#include <iostream>,而是使用printf()。通常在C++代码中您会这样做:

std::cout << "Char num of <" << text << "> = " << i << 'n';

您要做什么的工作示例:

int main()
{
    const char* text = "hello world"; // should be const char*
    int length = 0;
    for(const char* p = text; *p; ++p)
    {
        ++length;
    }
    std::cout << "Char num of <" << text << "> = " << length << 'n';
}

首先 - 不要在C 中使用char -string!使用std :: string。

您的way循环一直持续到它达到字符串终止为零,因此%s只是一个空字符串。'&lt;'即使字符串为空,也仍会打印'>'。

您的文本指针以以下字符开始:

'h','e','l','l','o',' ','w','o','r','l','d',''

第一个循环后,文本指向:

'e','l','l','o',' ','w','o','r','l','d',''

第二个循环后,文本指向:

'l','l','o',' ','w','o','r','l','d',''

等等。

while-loop继续进行,直到文本指向" 0",这只是一个空字符串,即。

因此,%s不打印任何东西。

在C 中:

int main() {
   std::string text = "hello world";
   cout << "Char num of <" << text << "> = " << text.size() << std::endl;
}

textchar的指针。因此,当您增加指针时,您可以指向下一个元素。C中的字符串的末端由空字符界定。因此,您将指针递增,直到指向空字符。之后,当您调用printf时,它不会打印任何东西,因为它会打印字符,直到达到null字符,但它已经处于空字符。
这可能是一个快速解决的方法:

#include <stdio.h>
int main() {
    char *text = "hello world";
    int i = 0;
    while (*text) {
        i++;
        text++;
    }
    printf("Char num of <%s> = %d", text-i, i);
}

循环指针text指向字符串字面的终止零,因为它在循环中增加了。

还在标题<cstdio>声明函数printf,C 中的字符串文字具有常数类型(尽管在C中,它们具有非恒定阵列的类型。但是,在两种语言中,您可能不会更改字符串文字)

) ) ) )

您可以重写程序喜欢

#include <cstdio>
int main() {
    const char *text = "hello world";
    int i = 0;
    while ( text[i] ) ++i;
    std::printf("Char num of <%s> = %dn", text, i);
}

或喜欢

#include <cstdio>
int main() {
    const char *text = "hello world";
    int i = 0;
    for ( const char *p = text; *p; ++p ) ++i;
    std::printf("Char num of <%s> = %dn", text, i);
}

也更好而不是C函数printf使用标准C 流操作员。

例如

#include <iostream>
int main() {
    const char *text = "hello world";
    size_t i = 0;
    for ( const char *p = text; *p; ++p ) ++i;
    std::cout << "Char num of <" << text << "> = " << i << std::endl;
}

最新更新