Reputation: 3
I have written the below code to find whether the string is a palindrome or not. In this, what i am trying to do is, first i reversing the string being stored in char 'a' and storing that reversed string in char 'b', but i am getting the error "Array must be initialized with a brace enclosed initializer" for char 'b'. Can someone please tell me what is wrong with my code and why i am getting the above error.
Code:
#include<stdio.h>
#include<string.h>
int main()
{
char a[100];
scanf("%s",&a[100]);
char b[100] = strrev(a);
if(a[100]=b[100])
{
printf("It is a palindrome");
}
else
{
printf("It is not a palindrome");
}
}
Upvotes: 0
Views: 799
Reputation: 50911
There are multiple issues in your code:
scanf("%s",&a[100])
is wrong, &a[100]
is the address of the 101st char in your array, you want the address of the first character, so it should be &a[0]
or simply a
.strcmp
for comparing strings. Read this for a more detailed explanationchar b[100] = strrev(a)
is wrong, you cannot assign entire arrays in C.Bonus:
scanf("%99s", ...
in order to avoid buffer overflows. 99 because your string can contain at maximum 99 characters + the null terminator.#include <stdio.h>
#include <string.h>
int main()
{
char a[100];
scanf("%s", a); // ask user for string and put it in a
char b[100];
strcpy(b, a); // copy a to b
strrev(a); // reverse a
if (strcmp(a, b) == 0) // compare a to b
{
printf("It is a palindrome");
}
else
{
printf("It is not a palindrome");
}
}
Upvotes: 1