Question: Sorry, I'm relatively new to c. What I'm trying to do is loop through a string and compare each char in the string to a char. If successful, I print some value. However I'm getting a segmentation fault.

**My Code:**

```
int i;
const char* perc = '%';
char mystr[7] = "hell%o";

for(i=0;i<sizeof(mystr);i++){
        if(strcmp(mystr[i],perc)!=0){
            printf("%d",i);
        }

```

**NOTE:** I'm not using **%** for format strings here, I'm literally just looking for its position in the string.

Thank you.

Answer: 
`strcmp()` is for comparing strings. To compare characters, you can use `==` operator.

Also note that `sizeof` is not for getting length of strings but getting number of bytes used for the type. In this case it is used for `char` array, so it may work according to what you want to do because `sizeof(char)` is defined to be `1` and therefore the number of bytes will be equal to the number of elements. Note that the terminating null-character and unused elements after that will added to the count if they exists. To get the length of string, you should use the [`strlen()`](https://man7.org/linux/man-pages/man3/strlen.3.html) function.

```
int i;
const char perc = '%'; /* use char, not char* */
char mystr[7] = "hell%o";
int len = strlen(mystr); /* use strlen() to get the length of the string */

for(i=0;i<len;i++){
        if(mystr[i] != perc){ /* compare characters */
            printf("%d",i);
        }

```
> 
> if(strcmp(mystr[i],perc)!=0){
> 
> 
> 

Must be `if(mystr[i]!= perc){`. And `const char* perc = '%';` should be `const char perc = '%';`

`strcmp` takes two strings (`char*`), but you are passing chars. Compiling with gcc and `-Wall` shows:

```
c.c: In function ‘main’:
c.c:5:20: warning: initialization of ‘const char *’ from ‘int’ makes pointer from integer without a cast [-Wint-conversion]
    5 | const char* perc = '%';
      |                    ^~~
c.c:9:24: warning: passing argument 1 of ‘strcmp’ makes pointer from integer without a cast [-Wint-conversion]
    9 |         if(strcmp(mystr[i],perc)!=0){
      |                   ~~~~~^~~
      |                        |
      |                        char
In file included from c.c:1:
/usr/include/string.h:137:32: note: expected ‘const char *’ but argument is of type ‘char’
  137 | extern int strcmp (const char *__s1, const char *__s2)
      |                    ~~~~~~~~~~~~^~~~

```

Always remember: The compiler is one of the best friends of you.

The fixed program could be:

```
#include <stdio.h>
#include <string.h>
int main() {
  int i;
  const char perc = '%';
  char mystr[7] = "hell%o";

  for (i = 0; i < sizeof(mystr); i++) {
    if (mystr[i] != perc) {
      printf("%d", i);
    }
  }
}

```