I am trying to make my own slice function, but for some value like (0,15) it is printing absurd value at the end. It is working fine for other inputs. Here is my code:
#include<stdio.h>
void slice(int a, int b, char *str) {
char new[b - a];
for (int i = 0; i < b - a; i ) {
new[i] = str[a i];
}
puts(new);
}
int main() {
char str[] = { "My name is Ayush Anand" };
slice(0, 15, str);
return 0;
}
What's wrong?
CodePudding user response:
There should be extra room for a null-terminator. So, at the (b - a)th index, add one.
for (int i = 0; i < b - a; i )
new[i] = str[a i];
new[b - a] = 0; // Null-terminator
As mentioned in one of the comments, a > b
is invalid. So, add a condition before the declaration of the new string.
if (a > b) {
fprintf(stderr, "a > b error");
return;
}
char new[b - a];
...