memset 和memcpy的作用

1.memset函数详细说明

  1. 功 能: 将s所指向的某一块内存中的每个字节的内容全部设置为ch指定的ASCII值,块的大小由第三个参数指定,这个函数通常为新申请的内存做初始化工作

    1. void *memset(void *s,int c,size_t n)<br />作用:将已开辟内存空间 s 的首 n 个字节的值设为值 c(给空间初始化);<br />**2.memcpy用法:**<br />void *memcpy(void *dest, const void *src, size_t n);<br />C语言需要包含头文件string.hC++需要包含cstring string.h<br />用法:用来将src地址处的内容拷贝n个字节的数据至目标地址dest指向的内存

    ```c

    include

    include

    include

    define N 10

int main() { int numbers = NULL; numbers = (int )malloc(Nsizeof(int)); printf(“\nMemory allocated at address: %p\n”, numbers); memset(numbers, 0, Nsizeof(int));

for(int i=0; i<N; i++){printf("%d ", numbers[i]);}

printf("\n");

char *strings1 = NULL;
char *strings2 = NULL;
strings1 = (char *)malloc(N*sizeof(char));
printf("\nMemory allocated at address: %p\n", strings1);

strings2 = (char *)malloc(N*sizeof(char));
printf("\nMemory allocated at address: %p\n", strings2);

memset(strings1, 'A', N*sizeof(char));
memset(strings2, 'I', N*sizeof(char));

for(int i=0; i<N; i++){printf("%c ", strings1[i]);}
printf("\n");
for(int i=0; i<N; i++){printf("%c ", strings2[i]);}

memcpy(strings2, strings1, N*sizeof(char));

printf("\nAfter memcpy:\n");
for(int i=0; i<N; i++){printf("%c ", strings1[i]);}
printf("\n");
for(int i=0; i<N; i++){printf("%c ", strings2[i]);}


free(numbers);
free(strings1);
free(strings2);

return 0;

}

```