Alvin
Alvin

Reputation: 950

warning: pointer/integer type mismatch in conditional expression

Following code is throwing

"warning: pointer/integer type mismatch in conditional expression".

How could I solve this?

#include<stdio.h>

int main()
{
    char *str = "Error";
    char *sch_str="pqrs";
    int i=1;

    if (i >= 0)
            str = (sch_str[i] != NULL) ? sch_str[i] : "Unknown";


    printf("%c\n",sch_str[i]);
    printf("%s\n",str);

    return 0;
}

Upvotes: 0

Views: 2033

Answers (6)

user2760375
user2760375

Reputation: 2558

better to use this

sch_str[i] != '\0'

and one more thing problem is in this whole

str = (sch_str[i] != NULL) ? sch_str[i] : "Unknown"; 

try to replace this with this

str = (sch_str[i] != '\0') ? "hello": "Unknown";

actually you are copying a single character in str when condition is true that is why it showing warning for that

Upvotes: 2

Sourav Ghosh
Sourav Ghosh

Reputation: 134316

1. sch_str[i] is not a pointer. Cannot compare it with NULL.
2. Cannot put [assign the value of] sch_str[i] into str

Upvotes: 5

Mike
Mike

Reputation: 126

Firstly you need to change char *str to const char and then the != '\0'

#include<stdio.h>

int main()
{
    const char *str = "Error";
    char *sch_str = "pqrs";
    int i=1;

    if (i >= 0)
            str = (sch_str[i] != '\0') ? sch_str : "Unknown";


    printf("%c\n",sch_str[i]);
    printf("%s\n",str);

return 0;
}

Upvotes: 0

user1508519
user1508519

Reputation:

The operands of the ternary operator must be convertible to the variable you're assigning it to.

char tmp[2] = { sch_str[i], '\0' };
str = (sch_str[i] != '\0') ? tmp : "Unknown";

Upvotes: 2

Chinna
Chinna

Reputation: 3992

sch_str[i] != NULL is a comparison between a character and NULL. You can't do it. For comparing with NULL it should be a pointer. char *sch_str="pqrs"; is a pointer to string "pqrs". Then sch_str[i] holds character not total string. You can do it by using sch_str[i] != '\0'.

Upvotes: 0

Drax
Drax

Reputation: 13278

(sch_str[i] != NULL)

You're testing a character against NULL, you have a logical error.

sch_str is a pointer to char, therfore sch_str[i] is a char. NULL represetns a null pointer, so this comparison has no sense.

Upvotes: 3

Related Questions