memcpy 使用demo
时间: 2024-03-05 12:45:55 浏览: 14
memcpy函数是C语言中的一个内存拷贝函数,用于将指定长度的数据从源地址复制到目标地址。它的函数原型如下:
```c
void *memcpy(void *dest, const void *src, size_t n);
```
其中,`dest`是目标地址的指针,`src`是源地址的指针,`n`是要拷贝的字节数。
下面是一个使用memcpy函数的示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Hello, CSDN";
char dest[20];
// 使用memcpy函数将src中的数据拷贝到dest中
memcpy(dest, src, strlen(src) + 1);
printf("拷贝后的字符串:%s\n", dest);
return 0;
}
```
在上面的示例中,我们定义了一个源字符串`src`和一个目标字符串`dest`,然后使用memcpy函数将源字符串拷贝到目标字符串中。最后,我们打印出拷贝后的目标字符串。
运行上述代码,输出结果为:
```
拷贝后的字符串:Hello, CSDN
```
这样就完成了从源地址到目标地址的内存拷贝操作。
相关问题
mmap使用demo
以下是一个使用mmap的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
int main() {
int fd;
struct stat buff;
char *map_ptr;
// 打开文件
fd = open("test.txt", O_RDWR);
if (fd == -1) {
printf("open error: %s\n", strerror(errno));
return -1;
}
// 获取文件大小
if (fstat(fd, &buff) == -1) {
printf("fstat error: %s\n", strerror(errno));
close(fd);
return -1;
}
// 映射文件到内存
map_ptr = mmap(NULL, buff.st_size+10, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
if (map_ptr == MAP_FAILED) {
printf("mmap error: %s\n", strerror(errno));
close(fd);
return -1;
}
// 使用映射区域
printf("mmap content1: %s\n", map_ptr);
memcpy(map_ptr, "LLL", 3);
printf("mmap content2: %s\n", map_ptr);
// 解除映射
if (munmap(map_ptr, buff.st_size+10) == -1) {
printf("munmap error: %s\n", strerror(errno));
close(fd);
return -1;
}
// 关闭文件
close(fd);
return 0;
}
```
使用时间戳调整 的demo
以下是使用时间戳调整的示例代码:
```
int frameRate = 30; // 设定的帧率
int inputFrameCount = 10; // 实际输入的帧数
int timeOffset = (1000000 / frameRate) * inputFrameCount; // 时间戳偏移量
for (int i = 0; i < inputFrameCount; i++) {
AMediaCodecBufferInfo info;
memset(&info, 0, sizeof(info));
info.offset = 0;
info.size = bufferSize;
info.presentationTimeUs = (i + 1) * timeOffset; // 加上时间戳偏移量
info.flags = 0; // 普通数据帧
uint8_t* inputBuffer = AMediaCodec_getInputBuffer(codec, i, &bufferSize);
memcpy(inputBuffer, data[i], dataSize);
AMediaCodec_queueInputBuffer(codec, i, 0, bufferSize, &info);
}
```
这段代码中,假设设定的帧率为 30,但是实际只能输入 10 帧数据。因此,需要根据时间戳偏移量进行调整,保证输出数据的帧率仍然维持在 30 帧每秒。偏移量的计算方式为:设定帧率的倒数乘以实际输入的帧数。在循环中,每次使用一个新的时间戳,并且加上时间戳偏移量,以保证时间戳的递增顺序。