問題描述
這是程序:
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模板網!