【问题标题】:Create an array when the size is a variable not a constant当大小是变量而不是常量时创建数组
【发布时间】:2019-12-13 12:02:00
【问题描述】:

这是程序:

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 就是为此而设计的。
  • newstd::vector 在这些情况下是你的朋友。
  • 我假设您使用 Sbuf 作为包含图像字节的数组,使用 unsigned char 而不是 char 会更好吗?
  • @Chipster new 在这种情况下可能不是 OP 的朋友。
  • @L.F.很公平。我的想法是,如果他们真的需要数组类型的东西并且不能满足于std::vector 之类的东西,那么这是一种创建可变长度数组的方法。我完全同意有更好的选择。

标签: c++ visual-studio


【解决方案1】:

没有正确的方法可以做到这一点,因为任何可变长度数组的程序都是ill-formed

可以说,可变长度数组的另一种选择是std::vector

std::vector<char> Sbuf;

Sbuf.push_back(someChar);

当然,我应该提一下,如果您专门使用charstd::string 可能适合您。 Here are some examples of how to use std::string,如果你有兴趣。

可变长度数组的另一种替代方法是new operator/keyword,尽管std::vector 如果可以使用它通常会更好:

char* Sbuf = new char[siz];

delete [] Sbuf;

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

【讨论】:

    【解决方案2】:

    您可以使用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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-27
      • 2019-08-02
      • 2011-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-05
      相关资源
      最近更新 更多