-1

I have created a function in C in order to count the amount of chars in the word that was input. I have debuged the code and all the variables are working properly. However when debuging the code and trying to use printf to present the result, an alert window pops up with the followig message: "Program Received Signal SIGSEV, Segmentation Fault". Please, could you help me address the problem, so the numer of chars are properly showed on the screen ? Down below is the code. Thanks.

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

int len(char v[]);

int main(){
    int x=0;
    char s[512];
    printf("Please input the word: ");
    gets(s);
    printf(len(s));
    return 0;
}



int len(char v[]){
    char h[512];
    int i=0;
    while(h[i]=v[i]){
        i++;    
    }
return i;

}
  • 2
    Enable; all compiler warnings to see why `printf(len(s));` is a problem. – chux - Reinstate Monica Nov 19 '20 at 02:48
  • And learn to use the debugger. At a minimum it will tell you exactly and instantly which line of code triggers the seg fault. – kaylum Nov 19 '20 at 02:49
  • Also, `while(h[i]=v[i])` the assignment in that statement is pointless and potentially more overhead than necessary since `h` is never actually used. Can just do `while(v[i])` – kaylum Nov 19 '20 at 02:50
  • Avoid using gets, check out why https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used – alex01011 Nov 19 '20 at 03:38

1 Answers1

0

You're missing your format specifier with the line: printf(len(s)). To see which one you need, look here

As someone was pointing out though, this problem could be approached better, so think of how you could improve your solution.

Visual Studio
  • 184
  • 1
  • 10