c - 为什么此代码会从 'char *' 错误分配到 'char'?

标签 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;
  }
}

最佳答案

我不喜欢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()字符串,但在这种情况下你不需要)。

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

关于c - 为什么此代码会从 'char *' 错误分配到 'char'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40458207/

相关文章:

丙 |套接字未正确关闭

javascript - 查找字符串中第一个不重复的字符,这里有什么错误?

c# - c# - 如何在c#中为字符串分配双倒(“)逗号?

c - 访问c中的不同驱动器

c - 有人愿意找出可能导致我的代码出现段错误的原因吗?

c - 自调用模块中的全局静态 int

在 go lang 中转换为结构类型

Java:检测字符串中是否存在单词

c - 是什么导致了这个段错误?

c - 为什么要使用pthread_exit?