将 char 缓冲区传递给函数并获取缓冲区的大小 [英] passing char buffer to functions and getting the size of the buffer

查看:39
本文介绍了将 char 缓冲区传递给函数并获取缓冲区的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将缓冲区大小设置为 100.我在声明缓冲区的主函数中显示缓冲区.但是,当我将缓冲区传递给函数并获得 sizeof '4' 时,我在想它应该是 100,因为那是我的缓冲区的大小在main中创建.输出:缓冲区大小:100大小(缓冲区):4

I have set the buffer to size 100. I display the buffer in the main function where the buffer is declared. However, when I pass the buffer to the function and get the sizeof '4', I was thinking it should be 100, as that is the size of the buffer that I created in main. output: buffer size: 100 sizeof(buffer): 4

#include <string.h>
#include <stdio.h>

void load_buffer(char *buffer);

int main()
{
    char buffer[100];
    printf("buffer size: %d
", sizeof(buffer));
    load_buffer(buffer);

    return 0;
}

void load_buffer(char *buffer)
{
    printf("sizeof(buffer): %d
", sizeof(buffer));
}

推荐答案

你使用的是缓冲区指针的大小(4字节),而不是缓冲区的大小.

You are using the size of the pointer to the buffer (4 bytes), rather than the size of the buffer.

在 C 中,您必须单独传递缓冲区的大小,这是缓冲区溢出如此容易和频繁发生的部分原因.

In C, you have to pass the size of the buffer separately, which is part of the reason buffer overruns happen so easily and frequently.

void load_buffer(char * buffer, size_t bufSize)
{    
    ...
}

这篇关于将 char 缓冲区传递给函数并获取缓冲区的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆