C++学习笔记 --- 指针1

活用指针进行for循环(多种写法),结果都是输出:“ Now is the time ”

#include <iostream>

// A character array.
char msg[] = "Now is the time\n";

////////////////////////////////////////
// The main() function.
////////////////////////////////////////
int main()
{
    char* cp;    // A pointer to char.
    int i;       // An integer subscript

    // Pointer access, pointer notation.
    for (cp = msg; *cp; cp++)
        std::cout << *cp;

    // Subscript access, subscript notation.
    for (i = 0; msg[i]; i++)
        std::cout << msg[i];

    // Pointer access, subscript notation.
    for (cp = msg; cp[0]; cp++)
        std::cout << cp[0];

    // Subscript access, pointer notation.
    for (i = 0; *(msg+i); i++)
        std::cout << *(msg+i);

    // Pointer and subscript access, pointer notation.
    for (i = 0, cp = msg; *(cp+i); i++)
        std::cout << *(cp+i);

    // Pointer and subscript access, subscript notation.
    for (i = 0, cp = msg; cp[i]; i++)
        std::cout << cp[i];

    return 0;
}


阅读更多
个人分类: C/C++专栏
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭