I've been crawling some codes on the internet and at a certain point I ended up with the functions memset
and memcpy
. I was able to understand superficially the functions of the mentioned functions, since all sources that provide some information or example code in relation to these two functions were somewhat similar and had enough basic information. However, I ended up asking the following questions:
- Is it wrong to use
memcpy
andmemset
with non-char data? - What is the utility of the void pointer returned by the
memset
function? - What is the utility of the void pointer returned by the
memcpy
function? -
Does
memcpy
only copy the data or does it also copy the address of the copied block?
Example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 10
#define NEW_SIZE 20
int main(void){
int *numbers=(int*)calloc(SIZE, sizeof(int));
for(unsigned int i=0; i<SIZE; i++){
numbers[i]=i+1;
}
for(unsigned int i=0; i<SIZE; i++){
printf("numbers[%d]=%d\n", i, numbers[i]);
}
printf("\n==================\n\n");
int *aux=(int*)realloc(numbers, NEW_SIZE*sizeof(int));
if(aux!=NULL){
memcpy(numbers, aux, NEW_SIZE*sizeof(int)); //isso é a mesma coisa que 'numbers=aux;' ???
for(unsigned int i=SIZE; i<NEW_SIZE; i++){
numbers[i]=i+1;
}
for(unsigned int i=0; i<NEW_SIZE; i++){
printf("numbers[%d]=%d\n", i, numbers[i]);
}
}
free(numbers);
return 0;
}