c++ - 如何使用新的 C++ 创建动态数组?
问题描述
我正在尝试动态初始化一个整数数组,因为数组的大小会根据输入而变化。程序如下:
int main()
{
int* list = createList("dis.bin");
for (int i = 0; i < sizeof(list) / sizeof(int); i++)
{
printf("%d\n", list[i]);
}
}
具有createList()
编写的功能:
int* createList(const char* file_name)
{
int counter = 1;
int* inst{};
FILE* myFile = fopen(file_name, "rb");
if (myFile == nullptr)
{
printf("\nFile not opened\n");
return 0;
}
int x = 0;
for (int i = 0; !(feof(myFile)); i++)
{
fread(&x, sizeof(int), 1, myFile);
inst = new int[counter];
inst[i] = x;
printf("%08x #%-4d | Int equiv: %-12d | Bin equiv: %s\n", x, counter, inst[i], ToBinary(inst[i], 0));
counter += 1;
x = 0;
}
return inst;
}
createList
从文件中读取.bin
(基本上包含一个字节数组)并将每对 4 个字节插入到数组中的一个项目中inst
。我通过根据counter
变量为数组分配新的空间来做到这一点。(所以无论值计数器变成数组的大小inst = new int[counter]
)然后我将给定索引处的数组内容设置为i
等于 x(读取的字节对)我会假设它createList
至少可以正常工作,因为printf
打印每个元素的语句inst[]
。
但是,当我调用createList("dis.bin")
main 并将其分配给变量int* list
时,我尝试遍历每个值。但这只是打印出一个未初始化的值(-842150451,如果你好奇的话)。所以我不确定我在这里做错了什么?
我应该提到我没有使用向量或任何标准容器。我只是在处理数组。我也printf
出于特定原因使用。
解决方案
这个问题被标记为 C++,但是 OP 正在显示 C 代码并说他们需要在 C 中使用它,所以我将在 C 中显示它......但前提是它使用new
而不是malloc
int* createList(const char* file_name, int& count)
{
// initialize count, so that way if we return early, we don't have invalid information
count = 0;
// open the file ad "READ" and "BINARY"
FILE* myFile = fopen(file_name, "rb");
if (!myFile)
{
printf("\nFile not opened\n");
return 0;
}
// calculate how many 4-byte integers exist in the file using
// the file length
fseek(myFile, 0, SEEK_END);
count = ftell(myFile) / sizeof(int);
rewind(myFile);
// allocate the memory
int* returnData = new int[count];
// read in 4-byte chunks to our array until it can't read anymore
int i = 0;
while (fread(&returnData[i++], sizeof(int), 1, myFile) == 1);
// close the file
fclose(myFile);
// return our newly allocated data
return returnData;
}
int main()
{
int count;
int* myInts = createList("c:\\users\\andy\\desktop\\dis.bin", count);
for (int i = 0; i < count; ++i) {
printf("%d\n", myInts[i]);
}
// don't forget to delete your data. (another reason a vector would be better suited... no one remembers to delete :)
delete myInts;
}
推荐阅读
- node.js - 如何计算目前我们一周的每日订单?
- c# - ASP.NET Core 奇怪的 URL 解析。单个查询字符串参数
- flutter - 如何在颤振 apk 中删除架构
- terraform - 解决 terraform 中损坏的已删除状态
- angular - 找不到“请求”的类型定义文件:node_modules/@looker/sdk-rtl/lib/oauthSession.d.ts:1:23 中的错误 - 错误 TS2688
- nginx - 将 https 反向代理到 http 后,在 nginx 中出现“502 Bad Gatway”错误
- sql - 选择具有不同字段的最后一行
- struct - 没有从实现 Rust 特征的结构推断出特征?
- controller - Phoenix - 控制器和视图之间的回调操作
- apache-kafka - 在同一个 Spring Kafka 应用程序中读取 JSON 和 String