【问题标题】:How can i fix this code in order to check if a number is palindrome, using pointers?如何修复此代码以使用指针检查数字是否为回文?
【发布时间】:2019-02-08 02:03:20
【问题描述】:

我对 C 语言很陌生。我不太了解如何正确使用指针。我知道不用指针也可以完成,但我必须使用它们

#include <stdio.h>
#include <stdlib.h>

void palindrome(int *n)
{
   int ok=0,*p,*m;
    m=n;
    while(*n!=0)
    {
        *p=*p*10+*n%10;
        *n=*n/10;
    }
    if (*m==*p) ok=1;
    if (*m!=*p) ok=0;

    if (ok==1)
        printf("Number is palindrome.");
    if (ok==0)
        printf("Number is not palindrome");
}

int main()
{
    int n;
    printf("Give value to n: ");
    scanf("%d",&n);

    palindrome(n);


}

预期的结果是,例如,数字 212 是回文,数字 312 不是回文

【问题讨论】:

  • 要正确格式化代码:粘贴代码,选择代码,按代码按钮{}。现在就点击问题下方的edit 链接试试吧。

标签: c pointers numbers palindrome


【解决方案1】:

这里是代码。我认为您应该在实际使用指针之前尝试了解指针的工作原理。我不想为您提供代码,但由于您是新手,所以我提供了一个工作代码。尝试了解它是如何工作的,而不是仅仅将这段代码复制粘贴到你必须放置的地方。

#include <stdio.h>
#include <stdlib.h>

void palindrome(int *n)
{
   int ok=0;
   int *p = (int *)malloc(sizeof(int));
   int *m = (int *)malloc(sizeof(int));
   *p=0;
    *m=*n;
    while(*n!=0)
    {
        *p=*p*10+*n%10;
        *n=*n/10;
    }
    if (*m==*p) ok=1;
    if (*m!=*p) ok=0;

    if (ok==1)
        printf("Number is palindrome.");
    if (ok==0)
        printf("Number is not palindrome");
}

int main()
{
    int n;
    printf("Give value to n: ");
    scanf("%d",&n);
    palindrome(&n);
    return 0;

}

【讨论】:

    【解决方案2】:

    @arpit-agrawal

    你忘了加免费,在末尾​​p>

    void palindrome(int *n)
    {
        ...
        free(p);
        free(m);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-06
      • 2011-09-05
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      • 2015-09-30
      • 1970-01-01
      • 2010-11-02
      • 1970-01-01
      相关资源
      最近更新 更多