bharath kumar reddy bharath kumar reddy - 1 month ago 18
C Question

Why is this code getting an assignment to 'char *' from 'char' error?

I am getting errors while compiling.

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


My Code:

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

Answer

I'm not fond of the CS50 typedef char *string; — it doesn't help enough and does cause far too much confusion. You can't declare arrays of characters using string.

This code works:

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

Changes are to string S = GetString(); in main(); char B[100]; in palin(); respelled 'palindrome'; use '\0' in place of "\0" (which has other problems too; it's the same as "" in this context, and that isn't how you compare strings (in the generic sense as well as the CS50 sense) — you need strcmp() if you want to compare strings, but you don't in this context).

It doesn't free the allocated string. It does produce the correct answers (program name 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
$