Can someone please explain me why I get "Segmentation fault..." and how to fix it on this bit of code?
#include<stdio.h>
int str_length(char *s) {
int length = 0, i;
for(i = 0; *s; i++) {
s++;
}
return i;
}
char *strdel(char *s, int pos, int n) {
int i;
char *p, str[] = "";
p = str;
for(i = 0; i < str_length(s) - n + 1; i++) {
if(i >= pos) {
*(p + i) = *(s + i + n);
}
else {
*(p + i) = *(s + i);
}
}
s = str;
return s;
}
int main() {
char *str = "abcdef";
printf("str_lengh: %d\n", str_length(str));
printf("strdel: %s\n", strdel(str, 1, 2));
return 0;
}
And I get this output:
str_lengh: 6
strdel: adef
Segmentation fault (core dumped)
Also, is there a better way to create a function: char *strdel(char *s, int pos, int n); that deletes the n characters from position pos than the one I did?