How to properly use memcpy? [duplicate]

2

I'm trying to create a program that will have two vectors:

char vetor_origem[20] = "algoritmo";
char vetor_copia[20]

As you can see, in vetor_origem I have the word algorithm written, and I want to copy the string from it to vetor_copia , I know that using memcpy() can do this, but I want much more than this.

I have a function called substring() where in it, the user will put the posição inicial and the quantidade of letters to be copied from vetor_origem to vetor_copia , but for documentation memcpy() says that it can only have 3 arguments, and I need 4 arguments. It would look like this, just the way I want it:

    char vetor_origem[20] = "algoritmo";
    char vetor_copia[20]
    substring(0,4) --> "algo"

It would copy from the starting position and the amount of letters, using memcpy() called by the function substring() .

How can I do this?

    
asked by anonymous 19.06.2017 / 17:39

1 answer

3

You can use memcpy so

char vetor_copia[20] = { 0 }; // Inicializa o vetor com terminador null
memcpy(vetor_copia, &vetor_origem[posicao_inicial], quantidade); // Copia os caracteres
  • posicao_inicial functions as an offset . Thus, the string will be passed to the function starting with the desired initial position
  • quantidade will indicate the amount of bytes that you want to copy. As each char takes 1 , passing this value to the function already resolves.

Example online here .

    
19.06.2017 / 17:53