0

Can someone explain to me why this code is constantly crashing. Everything seems fine to me.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* find(char *haystack, char needle);
int main (){
    char haystack[400], needle;
    fgets(haystack,400,stdin);
    scanf("%c", needle);
    if(find(haystack,needle)) printf("%ld", find(haystack, needle) - haystack);
    else printf(NULL);
    return 0;
}
char* find(char *haystack, char needle) {
    int lewski, cska;
    lewski = strlen(haystack);
    if(strchr(haystack,needle)){
        cska = lewski-strlen(strchr(haystack,needle));
        return &haystack[cska];
    }
    return NULL;
}
The Cat
  • 11
  • 1
  • 6
  • 3
    You could run in a debugger and find out yourself. – Some programmer dude Mar 17 '16 at 18:17
  • 3
    "Why does this C code crash?" - I would assume because there is a programming error in the code. If you told where and when it crashes, along with the **expected** behaviour, it might be easier to help you. See [ask]. – too honest for this site Mar 17 '16 at 18:21
  • You want to enable all compiler warnings, then take the warnings issued serious and fix the code. – alk Mar 17 '16 at 18:39
  • Also `strlen()` returns `size_t` not `int`. – alk Mar 17 '16 at 18:40
  • And if supported by your C implementation use the length modifier `t` leading to `"%td"` to print out a pointer difference. This way you make sure the correct width for pointers is assumed. – alk Mar 17 '16 at 18:44

1 Answers1

1

In your code you are not using scanf properly. Modify as follows;

scanf("%c", &needle);

Also printf doesn't print NULL Modify as follows;

printf("NULL");

Hope this helps.

Sudipta Kumar Sahoo
  • 1,049
  • 8
  • 16