易百教程

使用指针显示字符串

C语言没有字符串变量,它使用char数组来存储字符串。

示例代码

#include <stdio.h>

int main()
{
    char sample[] = "this is a test string?\n";
    char *ps = sample;

    while (*ps != '\0')
    {
        putchar(*ps);
        ps++;
    }
    system("pause");
    return(0);
}

执行上面示例代码,得到以下结果:

this is a test string?

消除冗余比较。参考以下示例代码:

#include <stdio.h>

int main()
{
    char sample[] = "this is a test string?\n";
    char *ps = sample;

    while(*ps)
        putchar(*ps++);
    return(0);
}

执行上面示例代码,得到以下结果:

this is a test string?

消除while循环中的语句,可将所有操作放在while语句的评估中。
putchar()函数返回显示的字符。

#include <stdio.h>

int main()
{
    char sample[] = "this is a test string?\n";
    char *ps = sample;

    while (putchar(*ps++))
        ;
    system("pause");
    return(0);
}

执行上面示例代码,得到以下结果:

this is a test string?