当大小是变量而不是常量时创建一个数组

Create an array when the size is a variable not a constant

本文关键字:一个 创建 数组 常量 变量      更新时间:2023-10-16

这是程序:

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以便代码编译?

没有正确的方法可以做到这一点,因为具有任何可变长度数组的程序都是格式错误的。

可以说,可变长度数组的替代方案是std::vector

std::vector<char> Sbuf;
Sbuf.push_back(someChar);

当然,我应该提到,如果您专门使用charstd::string可能适合您。如果您有兴趣,这里有一些如何使用std::string的示例。

可变长度数组的另一种替代方法是new运算符/关键字,尽管std::vector如果您可以使用它通常更好:

char* Sbuf = new char[siz];
delete [] Sbuf;

但是,此解决方案确实存在内存泄漏的风险。因此,std::vector是优选的。

您可以使用new关键字动态创建数组:

char* Sbuf; // declare a char pointer Sbuf
Sbuf = new char[siz]; // new keyword creates an array and returns the adress of that array
delete Sbuf; // you have to remember to deallocate your memory when you are done

更好,更标准的兼容方法是使用智能指针

std::unique_ptr<char[]> Sbuf = std::make_unique<char[]>(siz);
相关文章: