当大小是变量而不是常量时创建一个数组
Create an array when the size is a variable not a constant
这是程序:
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);
当然,我应该提到,如果您专门使用char
,std::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);
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 试图在visual studio上用C++创建一个桌面应用程序
- 如何创建一个空的全局类并在启动时实例化它
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何创建一个QTableWidgetItem,用长文本右对齐,左边有省略号
- 我正在尝试使用 c++ 创建一个货币转换程序,我不知道如何继续
- visual是否可以在c++中创建一个接收无限数量相同类型(或至少相当数量)参数的函数
- C++-我可以创建另一个类的成员并在构造函数中使用它吗
- 试图创建一个多线程程序来查找0-100000000之间的总素数
- 如何创建一个函数来计算并返回平均值、最大值和最小值
- 如何使用CLion在Mac上创建一个新的.txt文件
- 如何在没有数据拷贝的情况下从指针创建一个Eigen VectorXd对象
- 在c++中为double类型的数组创建一个unique_ptr
- 如何创建函数管道,以便函数一个接一个地运行?
- 如何从这些语句中的每一个创建不同的函数?
- 给定一个创建的带有货物的链表,我需要使用函数检查实际序列或"train"是否有效
- 一个创建彩票游戏的程序,该彩票游戏可以有效地创建 10 套而没有任何重复?
- 如何实现一个创建新对象并返回对它的引用的C++方法
- 如何成功创建一个创建对象并返回指向该对象的指针的函数