【问题标题】:Using pointers to navigate an array, instead of using an int使用指针导航数组,而不是使用 int
【发布时间】:2015-04-10 06:42:50
【问题描述】:

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

#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;
}

【问题讨论】:

  • 你能告诉我们你的尝试吗?
  • 不清楚你真正想要什么。你可以有一个指向你的数组的指针并取消引用它来存储值
  • 我发布了我尝试过的内容,我只是一开始没有上传它,因为它太糟糕了。它只需要输入的第一个字母,然后跳过其余的。不知道为什么会这样。

标签: c arrays loops pointers


【解决方案1】:

大概是这样的:

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

printf("The reverse order is: ");

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

代码未经测试。

【讨论】:

  • 在此之后,endptr 将指向characterArray[-1],即UB。
  • @glglgl : endptr 只会指向characterArray[-1],只要你不取消引用它,这不是未定义的行为。否则char *x = NULL 也将是未定义的行为。
【解决方案2】:
#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;
}

【讨论】:

  • 您能向我解释一下您的代码吗:)?
【解决方案3】:

这是一个演示程序

// 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

【讨论】:

  • 感谢您的快速回复,我会花时间研究这个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-30
  • 2013-12-20
  • 2011-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多