c语言 - 为什么此代码从错误中获得'char *' 'char'赋值?



在编译时出现错误。

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 analyzen");
  string S[10];
  S = GetString();
  int flag = pallin(S);
  if(flag == 0)
  {
    printf("Invalid inputn");
  }
  else if (flag == 1)
  {
    printf("Yes, the input is a pallindromen");
  }
  else{
    printf("The input is not a pallindromen");
  }
}
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]!="")
         {
         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;
  }
}

我不喜欢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 analyzen");
    string S = GetString();
    int flag = palin(S);
    if (flag == 0)
    {
        printf("Invalid inputn");
    }
    else if (flag == 1)
    {
        printf("Yes, the input is a palindromen");
    }
    else
    {
        printf("The input is not a palindromen");
    }
}
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] != "")
        while (A[i] != '')
        {
            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;
    }
}

main()string S = GetString();的变化;char B[100]; in palin();respelled"回文";使用''代替""(这也有其他问题;在这个上下文中,它与""相同,并且这不是比较字符串的方式(在一般意义上以及CS50意义上)-如果您想比较字符串,您需要strcmp(),但在这个上下文中您不需要)。

它不会释放已分配的字符串。它确实产生正确的答案(程序名称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
$

最新更新