【问题标题】:C: Read ints from file and store in pointer arrayC:从文件中读取整数并存储在指针数组中
【发布时间】:2018-09-26 20:20:51
【问题描述】:

我正在尝试从文件中读取整数并将它们存储在数组中。然后,我想将这些值写入不同的文件。读取写入是在与创建数组的主文件不同的文件中完成的。我无法更改函数的参数(这是用于赋值,因此数组参数必须是 int** ppPerm)。该函数在另一个文件的主函数中被调用,并且最初创建的数组。我正在读取的文件如下所示:

15
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

其中 15 是后面的数字。所以函数的时间顺序是:

Array Perm 在主文件的 main 函数中创建(int* Perm = NULL)。它被传递到 readP()

readP(In, &Perm);

文件中的数字被读取并存储在 Perm 中。然后将相同的变量 Perm 传递给 writeP()。

writeP(Out, Perm, permLength);

Perm 被读取并写入不同的文件。 我无法更改其中任何一条。在路上的某个地方,阵列被搞砸了。这里是 readP()。

int readP(FILE* In, int** ppPerm) {
   int numElements = 0;

   fscanf(In, "%d", &numElements);

   *ppPerm = (int*)calloc(numElements, sizeof(int));

   int i;
   for (i = 0; i < numElements; i++) {
       fscanf(In, "%p", &ppPerm[i]);
   }

   return numElements;
}

现在,该数组完全不可读。无论出于何种原因,存储的数字类似于 0x0,然后是随机的十六进制混杂。然后在 writeP() 中使用该数组将值写入不同的文件:

void writeP(FILE* Out, const int* pPerm, int permLength) {

    int i = 2;
    for (i = 0; i < permLength; i++) {
        fprintf(Out, "%d ", pPerm[i]);
    }

    return;
}

int* pPerm 与传入 readP() 的数组相同。出于某种原因,使用调试,我看到 pPerm 包含与 ppPerm 完全不同的值,并且在某些情况下它似乎是半空的。我的功能到底有什么问题?为什么我不能正确地将数字存储在数组中?为什么数组总是在 readP() 和 writeP() 之间搞乱?

【问题讨论】:

  • 有什么问题?
  • fscanf(In, "%p", &amp;ppPerm[i]); 应该是fscanf(In, "%d", &amp;(*ppPerm)[i]);
  • @kiranBiradar 为什么将答案作为评论发布?
  • @Swordfish 我正在使用移动设备。所以我不能打字。
  • @Kiran Biradar 谢谢!我相信做到了。

标签: c arrays file


【解决方案1】:

不要在 C 中转换 calloc()malloc() 的结果!它可以隐藏错误。

int i;
for (i = 0; i < numElements; i++) {
    fscanf(In, "%p", &ppPerm[i]);
}

由于您要读取整数,格式字符串应为"%i""%d"。要获得指向您分配的内存的指针,请使用*ppPerm

size_t i;  // variables that hold an index into or the size
           // of objects in memory should be of type size_t.
for (i = 0; i < numElements; i++) {
    fscanf(In, "%p", &(*ppPerm)[i]);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    • 1970-01-01
    • 2023-01-19
    • 1970-01-01
    相关资源
    最近更新 更多