Ayush Kumar
Ayush Kumar

Reputation: 13

Why is my slice function not working in C?

Recently I tried to make a slice function using C, and it is not working as I intend it to so I want to know why it is not working. I want the function only to print the specified section of the string (slicing of string).

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

void slice(char s[], int start, int end);

void slice(char s[], int start, int end);
int main(){
    char s[500];
    printf("enter the full sentence/word \n");
    fgets(s, sizeof(s), stdin);
    int start, end;
    printf("enter the start of slicing ");
    scanf("%d", start);
    
    printf("enter the end of slicing ");
    scanf("%d", end);
    slice(s, start, end);


}

void slice(char s[], int start, int end){
   
    for(int i= start; i <= end; i++){
       
        printf("%c", s[i]);
        
    }
    
}

Upvotes: 0

Views: 78

Answers (1)

babon
babon

Reputation: 3774

This scanf("%d", start); is wrong. You need to write to the address of the variable with &start. Same goes for scanf("%d", end);.

More specifically, your program invokes UB as you are trying to access memory you do not own.

Upvotes: 2

Related Questions