C语言使用指针打印字符串的程序

编写一个C程序,使用指针打印字符串。通常,我们使用循环来迭代字符串数组的每个字符索引。在本例中,我们将字符串数组的地址赋给指针。接下来,我们使用while循环通过递增指针来打印每个字符。

#include <stdio.h>

int main()
{
    char str[100];
    char *ch;

    printf("Please Enter String to print = ");
    fgets(str, sizeof str, stdin);

    ch = str;
    printf("\nPrinting Given String using Pointers\n");
    while(*ch != '\0')
    {
        printf("%c", *ch++);
    }
}
C program to Print String using Pointer

这个C程序使用for循环,并通过指针打印字符数组。在本示例中,我们通过创建一个接受指针并打印字符串的printString函数展示了另一种选择。

#include <stdio.h>
void printString(char *ch)
{
    while(*ch != '\0')
    {
        printf("%c", *ch++);
    }
}
int main()
{
    char str[100];
    char *ch;

    printf("Please Enter Text = ");
    fgets(str, sizeof str, stdin);

    for(ch = str; *ch != '\0'; ch++)
    {
        printf("%c", *ch);
    }
    printString(str);
}
Please Enter Text = programs output

programs output
programs output