Home > Blockchain >  How can I copy from a c string into an array and then limit the amount returned while also adding a
How can I copy from a c string into an array and then limit the amount returned while also adding a

Time:09-05

I'm trying to implement a function that copies characters from the c string source and then stores it into the array destination. I know this is strcpy however I am not allowed to call in any functions and am not allowed to use any local variables. I also have to be able add on a null terminator on the end of it so that the array becomes a c string itself. numChars is the size that the array destination is being limited to. for example if source was "apples" and numChar was 2, the first 3 elements would be 'a', 'p' and '\0'. Below is my attempt, how would I go about this?

void copyWord(char * destination, const char * source, int numChars){
    
    while(*destination != numChars){
        *destination = *source;
        destination  ;
        source  ;
    }
    destination[numChars] = '\0';
}

CodePudding user response:

What you describe is basically strncpy, but your own implementation:

void copyWord(char *destination, const char *source, int destSize) {

    if ((destination == nullptr) || (destSize <= 0))
    {
        return;
    }

    while ((destSize > 1) && (*source)) {
        *destination = *source;
        destination  ;
        source  ;
        destSize--;
    }

    // destSize is at least 1, so this is safe
    *destination = '\0';

}

CodePudding user response:

Here is my attempt solution:

void copyWord(char * destination, const char *source, int numChars){
    if(!numChars){
         *destination = '\0';
         return;
    }
    while(*source != NULL && numChars --){
        *destination = *source;
        destination  ;
        source  ;
    }
    *destination = '\0';
}

CodePudding user response:

Something like this should do the trick, you probably should add some error checks as well checking the arguments to the function.

void copyWord(char * destination, const char * source, int numChars)
{
    while(numChars-- && *source) 
    {
        *destination   = *source  ;
    }
    *destination = '\0';
}
  • Related