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

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

问题描述

这是程序:

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);

当然,我应该提一下,如果您特别使用 charstd::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.

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

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