Create an array when the size is a variable not a constant(当大小是一个变量而不是一个常量时创建一个数组)
问题描述
这是程序:
int siz = 0;
int n = 0;
FILE* picture;
picture = fopen("test.jpg", "r");
fseek(picture, 0, SEEK_END);
siz = ftell(picture);
char Sbuf[siz];
fseek(picture, 0, SEEK_SET); //Going to the beginning of the file
while (!feof(picture)) {
n = fread(Sbuf, sizeof(char), siz, picture);
/* ... do stuff with the buffer ... */
/* memset(Sbuf, 0, sizeof(Sbuf));
}
我需要读取文件大小.我确信这段代码是在另一个编译器上编译的.如何正确声明 siz
以便代码编译?
I need to read the file size.
I know for sure that this code compiled on another compiler.
How to correctly declare siz
correctly so that the code compiles?
推荐答案
没有正确的方法可以做到这一点,因为具有任何可变长度数组的程序是 格式错误.
There is no proper way to do this, as a program with any variable length array is ill-formed.
可以说,可变长度数组的替代方案是 std::vector
:
An alternative, so to speak, to a variable length array is a std::vector
:
std::vector<char> Sbuf;
Sbuf.push_back(someChar);
当然,我应该提一下,如果您特别使用 char
,std::string
可能适合你.以下是一些如何使用 std::string
的示例,如果你有兴趣.
Of course, I should mention that if you are using char
specifically, std::string
might work well for you. Here are some examples of how to use std::string
, if you're interested.
可变长度数组的另一种替代方法是 new
操作符/关键字,尽管 std::vector
如果你可以使用它通常会更好:
The other alternative to a variable length array is the new
operator/keyword, although std::vector
is usually better if you can make use of it:
char* Sbuf = new char[siz];
delete [] Sbuf;
但是,此解决方案确实存在内存泄漏的风险.因此,std::vector
是首选.
However, this solution does risk memory leaks. Thus, std::vector
is preferred.
这篇关于当大小是一个变量而不是一个常量时创建一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:当大小是一个变量而不是一个常量时创建一个数


基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01