当大小是变量而不是常量时创建一个数组 [英] Create an array when the size is a variable not a constant

查看:87
本文介绍了当大小是变量而不是常量时创建一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是程序:

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.

可变长度数组的另一种替代方法是

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.

这篇关于当大小是变量而不是常量时创建一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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