[Solved] c search for target string in string [closed]


Looking at the error messages is sufficient to debug the code and make it work. It’s very basic error messages that can be resolved just by reading the code once.

1)

extern.c:14:7:conflicting types for ‘array’
 char *array[5][0];
       ^~~~~
extern.c:6:6: note: previous declaration of ‘array’ was here
 char array[5][10];

Error: There is declaration of same variable twice. So remove one declaration (line 14).

2)

      ^~~~~
extern.c:16:1: error: ‘length’ undeclared (first use in this function)
 length=strlen(array[i][0]);
 ^~~~~~
extern.c:16:1: note: each undeclared identifier is reported only once for each function it appears in

Error: variable length is undeclared. So declare it (int length)

3)

extern.c:17:11: warning: passing argument 1 of ‘strcmp’ makes pointer from integer without a cast [-Wint-conversion]
 if(strcmp((array[i][length-2],"ed")==0)
           ^
In file included from extern.c:2:0:

/usr/include/string.h:136:12: note: expected ‘const char *’ but argument is of type ‘int’
 extern int strcmp (const char *__s1, const char *__s2)
            ^~~~~~
extern.c:17:4: error: too few arguments to function ‘strcmp’
 if(strcmp((array[i][length-2],"ed")==0)
    ^~~~~~
In file included from extern.c:2:0:
/usr/include/string.h:136:12: note: declared here
 extern int strcmp (const char *__s1, const char *__s2)

It is clear that strcmp expects const char * but you are giving integer. array[i][length-2] refer to a character in the string. So give as &array[i][length-2] inside strcmp to give the address of the second last element. Same case with the strlen. Also ) mismatch is throwing too few arguments error in if(strcmp((array[i][length-2],"ed")==0) (Its very trivial, there are 3 ( and 2 ), just look in the code)
.

4)
Also } mismatch is there in the program.

So finally after resolving the errors, it should look something like this:

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

int main()
{
    char array[5][10];
    int i;

    for( i = 0; i < 5; i++ ) 
    {
        printf("%s", "enter a string"); //enter string
        scanf("%10s", array[i]);
    }
    for( i = 0; i < 5; i++ )
    {
        size_t length = strlen(array[i]);
        if(strcmp(&array[i][length-2], "ed") == 0)
        {
            printf("%s\n",array[i]);
        }
    }

    return 0;
}

2

solved c search for target string in string [closed]