c_cpp C中带有读指针的动态缓冲区示例
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp C中带有读指针的动态缓冲区示例相关的知识,希望对你有一定的参考价值。
#include <stdio.h>
#include <stdlib.h>
// C dynamic buffer with reader pointer.
// Macro to expand buffer.
#define Buf_EXPAND(buf, amount) \
buf->cap += amount; \
buf = realloc(buf, sizeof(Buf) + buf->cap)
typedef struct
{
size_t len;
size_t cap;
unsigned char* reader;
unsigned char data[0];
} Buf;
Buf* Buf_new(size_t reserve)
{
Buf* newbuf = malloc(sizeof(Buf) + reserve);
newbuf->len = 0;
newbuf->cap = reserve;
newbuf->reader = newbuf->data;
return newbuf;
}
void Buf_print(Buf* b, int amount)
{
while(amount--)
{
printf("%u\n", *(b->reader));
b->reader++;
}
}
// Checks if reader is at end
int Buf_reader_end(Buf* b)
{
return b->reader == (b->data + b->cap);
}
int main(void) {
Buf* c = Buf_new(10);
printf("Reader @ = %p\n", c->reader);
c->data[0] = 55;
Buf_print(c, 2);
printf("Reader moved = %lu\n", c->reader - c->data);
printf("Reader is at end %d\n", Buf_reader_end(c));
free(c);
return 0;
}
以上是关于c_cpp C中带有读指针的动态缓冲区示例的主要内容,如果未能解决你的问题,请参考以下文章
c_cpp C ++中的char指针示例
c_cpp c中带字符串和char数组的基本io
c_cpp c中带字符串和char数组的基本io
c中带有无符号字符的空指针
C中带有双指针的代码
C指针原理(20)-C指针基础