[英]How can I initialize an empty Buffer in C language
I'm doing a work in wish I have to read caracters from a File, and save them in a buffer. 我正在做一个工作,希望我必须从文件中读取角色,并将其保存在缓冲区中。 Later i have to output them, but for know I'm still struggling with the buffer thing.
以后我必须输出它们,但是知道我仍然在为缓冲工作。 I would like to know how can I initialize the buffer(empty of course) and then put caracters into that buffer.
我想知道如何初始化缓冲区(当然是空的),然后将角色添加到该缓冲区中。 I want to do it in another function who is called by int main(..).Here's waht I have:
我想在另一个由int main(..)调用的函数中执行此操作。
buffer_t initBuffer(void) {
// Reserves space for the buffer, ends program if it cant reserve space.
buffer_t buffer = malloc(sizeof(*buffer));
if (buffer == NULL) {
printf("Error allocating bufefr\n");
exit(1);
}
after this, how can I initialize it with his counter at 0? 之后,如何用他的计数器为0初始化它?
Definition of buffer_t
: buffer_t
定义:
typedef struct buffer_s *buffer_t;
struct buffer_s {
unsigned char buffer[BUF_SIZE];
counter;
}
There are two apprroaches for two different needs. 有两种方法可以满足两种不同的需求。 Choose whichever suits your requirement.
选择适合您的要求。
If you want to initialize your allocated memory area to 0
, you can use calloc()
to directly do that (allocate and initialize to 0
). 如果要将分配的内存区域初始化为
0
,则可以使用calloc()
直接执行该操作(分配并初始化为0
)。
If you want to initialize your allocated buffer to some other value, you can use memset()
after doing a malloc()
. 如果您想将分配的缓冲区初始化为其他值,你可以使用
memset()
做了之后malloc()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.