I'm learning C programming language and I'm trying to create a function which makes a substring and then returns it. I found this code here:
void substring(char s[], char sub[], int p, int l) {
int c = 0;
while (c < l) {
sub[c] = s[p+c-1];
c++;
}
sub[c] = '\0';
}
I want to get rid of the char sub[] in parameters and instead return a string created inside of the function.
This is the closest (I think) think I got, but I always get a segmentation fault (core dumped) runtime error.
char substring(char s[], int p, int l) {
int c = 0;
char sub[1000];
while (c < l) {
sub[c] = s[p+c-1];
c++;
}
sub[c] = '\0';
return *sub;
}
Thanks for any help
malloc.char* SubString = s + p;where p is the start position. IF you really need a copy later time, I wouldn't reinvent the wheel and use one of predefined methods likememcpy(MySubStringCopy, SubString, l);VariableMySubStringCopycould be locally stack allocated or heap allocated.