这是程序:
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.
这篇关于当大小是一个变量而不是一个常量时创建一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何在 Visual Studio 2008 中为我的应用程序设置图标How do I set the icon for my application in visual studio 2008?(如何在 Visual Studio 2008 中为我的应用程序设置图标?)
将 CString 转换为 const char*Convert CString to const char*(将 CString 转换为 const char*)
默认情况下,在 Visual Studio 中从项目中删除安全Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio(默认情况下,在 Visual Studio 中从项目中删除安全
如何在 Visual Studio 2008 中启动新的 CUDA 项目?How do I start a new CUDA project in Visual Studio 2008?(如何在 Visual Studio 2008 中启动新的 CUDA 项目?)
从 DLL 导出包含 `std::` 对象(向量、映射等)的类Exporting classes containing `std::` objects (vector, map etc.) from a DLL(从 DLL 导出包含 `std::` 对象(向量、映射等)的类)
发布版本与调试版本的运行方式不同的一些原因What are some reasons a Release build would run differently than a Debug build(发布版本与调试版本的运行方式不同的一些原因是什么