How to properly use memcpy?

Asked

Viewed 2,788 times

2

I’m trying to create a program where it will have two vectors :

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

In what can be seen, in the vetor_origem I have the word algorithm written, and I want to copy its string to the vetor_copia, I know using memcpy() it is possible to do this, but I want much more than this.

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

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

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

How can I do this ?

  • Example tested: https://pastebin.com/vp48Hizz

1 answer

3


You can use memcpy thus

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 a offset. Thus, the string will be passed to the function starting with the desired initial position
  • quantidade shall indicate the amount of bytes you want to copy. Like each char occupies 1 byte, pass this value to the function already solves.

Online example here.

  • 1

    Thank you very merchant, it worked the way I was wanting, I just wasn’t sure how to put it this way.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.