为什么这段代码会被赋予' char *'来自' char'错误?

时间:2016-11-07 05:10:46

标签: c string cs50

我在编译时遇到错误。

incompatible integer to pointer conversion assigning to 'string'
      (aka 'char *') from 'char'; take the address with &

我的代码:

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

int pallin(string A);
int main(void)
{
  printf("Enter the string to analyze\n");
  string S[10];
  S = GetString();
  int flag = pallin(S);
  if(flag == 0)
  {
    printf("Invalid input\n");
  }
  else if (flag == 1)
  {
    printf("Yes, the input is a pallindrome\n");
  }
  else{
    printf("The input is not a pallindrome\n");
  }
}

int pallin(string A)
{
  int flag;
  int n = strlen(A);
  if(n<=1)
  {
    return 0;
  }
  else 
  {string B[10];int i = 0;

         while(A[i]!="\0")
         {
         B[i]=A[n-i-1];  //Getting error here.
         i++;
         }

      for(int j = 0; j < n; j++)
      {
          if(B[j]!=A[j])
          {
              flag = 2;
          }
          else
          {
              flag = 1;
          }
      }
      return flag;
  }
}

1 个答案:

答案 0 :(得分:0)

我不喜欢CS50 typedef char *string; - 它没有足够的帮助,确实引起了太多的混乱。您无法使用string声明字符数组。

此代码有效:

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

int palin(string A);

int main(void)
{
    printf("Enter the string to analyze\n");
    string S = GetString();
    int flag = palin(S);
    if (flag == 0)
    {
        printf("Invalid input\n");
    }
    else if (flag == 1)
    {
        printf("Yes, the input is a palindrome\n");
    }
    else
    {
        printf("The input is not a palindrome\n");
    }
}

int palin(string A)
{
    int flag;
    int n = strlen(A);
    if (n <= 1)
    {
        return 0;
    }
    else
    {
        char B[100];
        int i = 0;

        //while (A[i] != "\0")
        while (A[i] != '\0')
        {
            B[i] = A[n - i - 1]; // Getting error here.
            i++;
        }

        for (int j = 0; j < n; j++)
        {
            if (B[j] != A[j])
            {
                flag = 2;
            }
            else
            {
                flag = 1;
            }
        }
        return flag;
    }
}

string S = GetString();中的main()进行了更改; char B[100];中的palin();被驱逐的'回文';使用'\0'代替"\0"(也有其他问题;在此上下文中它与""相同,而不是比较字符串的方式(在一般意义上也是如此)正如CS50意义上的那样 - 如果你想比较字符串,你需要strcmp(),但在这种情况下你不需要。{/ p>

它不释放分配的字符串。它确实产生了正确的答案(程序名称pa19):

$ pa19
Enter the string to analyze
amanaplanacanalpanama
Yes, the input is a palindrome
$ pa19
Enter the string to analyze
abcde
The input is not a palindrome
$ pa19
Enter the string to analyze

Invalid input
$
相关问题