Home > Software design >  Given a char array buffer of length n delete m characters from position pos
Given a char array buffer of length n delete m characters from position pos

Time:03-26

I want to delete characters from a unsigned char buffer

C language:

unsigned char buff[n] = "...."; // len n byte array

I thought of using memmove

memmove(buff   pos, buff   pos   m, ???);

Can anyone help with what should the value of ??? be, I am getting the correct result of m characters deleted irrespective of ??? value (any value between n - pos to n)

Values of m and pos are less than n and the buff is a byte array (A data packet)

CodePudding user response:

well this code is not optimized at all but shows what i think is the easiest to understand method:


#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void delete(int p, const char * str){
    char *done;
    int t = strlen(str); 
    if(p>t||p<=0){
        return; 
    }else{
        strcpy(done, str);
        strcpy(done p-1,str p); 
    }
    strcpy(str, done);
}
int main(int argc, char **argv){
    char buff[] = "abcdefghi"; 
    delete(3, buff); 
    printf(buff);//it prints abcdefghi
    return 0;
}

The idea is simple strcpy takes two parameters the first being a pointer to the destination string(str) and the second a pointer to origin.

we start by copying the whole original string(str) to our temporary string(done)

Then we just copy str p ( p being the position on the string starting at 1 and ending at strlen, since strlen excludes the terminator byte we check till the last position) to done p-1 as we want to erase/overlap the char at the position p

Finally we just copy done, to the original string(str) and we have successfully erased a character


Also since we are using strcpy, the function takes care of the terminator byte, we also don't have to pay much attention to freeing the temporary pointer although the compiler will complain about the casting of the origin string's which are fairly simple to resolve but to keep it easy to figure out the logic I've kept out of the answer

  • Related