使用指针导航数组,而不是使用int

时间:2015-04-10 06:42:51

标签: c arrays loops pointers

如何在程序中使用指针来跟踪数组的当前位置,而不是使用“counter”?

#include <stdio.h>
#include <string.h>

#define MAX 100

int main(void){

int counter = 0, c;
char *charPtr, characterArray[MAX] = { 0 };

printf("Enter a message: ");

for (c = getchar(); c != EOF && c != '\n'; c = getchar()){
    charPtr = &characterArray[0];
    characterArray[*charPtr++] = c;
}

counter = strlen(characterArray) - 1;
printf("The reverse order is: ");

while (counter >= 0){
    printf("%c", characterArray[counter]);
    --counter;
}
printf("\n\n");

return 0;
}

3 个答案:

答案 0 :(得分:2)

大致相同:

char *endptr = characterArray + strlen(characterArray) - 1;

printf("The reverse order is: ");

while (endptr >= characterArray){
    printf("%c", *endptr--);
}

代码未经测试。

答案 1 :(得分:1)

#include <stdio.h>
#include <string.h>

#define MAX 100

int main(void){

        int  c;
        char characterArray[MAX] = { 0 };
        char *ptr = NULL;
        ptr = characterArray;

        printf("Enter a message: ");

        for (c = getchar(); c != EOF && c != '\n'; c = getchar()){
                *ptr = c;
                ptr++;
        }
                *ptr = '\0';
        printf("The reverse order is: ");

        while ( ptr != characterArray ){
                printf("%c", *ptr);
                --ptr;
        }
        printf ( "%c",*ptr);
        printf("\n\n");

        return 0;
}

答案 2 :(得分:1)

这是一个示范程序

// This program takes the user input then reverses it. 
#include <stdio.h>

#define MAX 100

int main(void)
{
    char characterArray[MAX] = { 0 };
    char *p = characterArray;
    char c;

    printf("Enter a message: ");

    for ( c = getchar(); c != EOF && c != '\n'; c = getchar() )
    {
        *p++ = c;
    }

    printf("The reverse order is: ");

    while ( p != characterArray )
    {
        printf( "%c",  *--p );
    }

    printf( "\n\n" );

    return 0;
}

如果要输入

Hello, World

然后输出

dlroW ,olleH