Parias Lunkamba Mukeba
Parias Lunkamba Mukeba

Reputation: 302

string handling in C with pointer

this my code and when i run it using gcc compiler on linux machine and still showing those eroor bellow

#include<stdio.h>
#include<string.h>

 int is_in_f(char *s, char c) {
 while(*s) {
    if(*s==c) return 1;
    else s++;
}
return 0;
}

int main() {
char *name = "paria llls";
char string1[] = "a";
if(is_in_f(*name, string1)){
    printf("found");
}

return 0;
}

this my error

 E2.c: In function ‘main’:
 E2.c:14:19: warning: passing argument 2 of ‘is_in_f’ makes integer from          pointer without a cast [-Wint-conversion]
  if(is_in_f(name, string1)){
               ^~~~~~~
E2.c:3:5: note: expected ‘char’ but argument is of type ‘char *’
int is_in_f(char *s, char c) {

Upvotes: 0

Views: 59

Answers (2)

Siraj Alam
Siraj Alam

Reputation: 10025

When you're calling the function is_in_f(), you are passing name* which is a character as the variable name is a pointer variable. And you are defined in the function definition as the char *s, which is an address to the character in pointer variable are incompatible.

In the second parameter at the time of calling, you're passing the starting address of the array of character string1 and defined as the char, so here also they are incompatible.

Check this working code, a little modified of yours. Hope it helped.

#include<stdio.h>
#include<string.h>

 int is_in_f(char *s, char *c) {
 while(*s) {
    if(*s==*c) return 1;
    else s++;
}
return 0;
}

int main() {
char *name = "paria llls";
char string1[] = "a";
if(is_in_f(name, string1)){
    printf("found");
}

return 0;
}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

You made two errors in your call:

  • When you pass a pointer to a parameter that needs a pointer of the same type, do not use dereference operator *, and
  • The type for variables that keep a single character is char, not array of char. Constants of type char are delimited with single quotes instead of double quotes.

Hence, the calling code should be as follows:

char *name = "paria llls";
char char1 = 'a'; // <<== Note single quotes
if(is_in_f(name, char1 )) { // <<== No asterisk
    ...
}

Upvotes: 1

Related Questions