Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Making my own slice function for c but getting absurd value for some slices

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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];
...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading