c - gcc 数组中的值不一致

标签 c arrays gcc

我正在查看其他问题,但找不到与我的问题相关的任何问题。基本上我正在编写一段代码来读取一些带有数据的文本文件并稍后对其进行处理。但我面临一些奇怪的问题,数组中的值不断变化。下面我给出了两个“for”循环,其中一个循环是我从文件指针读取值并立即使用 printf 语句检查它。下一个“for”循环是我再次检查存储的值的地方,由于某种原因它是不同的,有一些随机值。

        for (int i = 0; i < ndihedrals; ++i)
        {
            fscanf (readdihedral, "%d %f %d %d %d %d\n", &sino_dih[i], &angle_dih[i], &atom1_dih[i], &atom2_dih[i], &atom3_dih[i], &atom4_dih[i]);
            printf("i: %d ==> %d %f %d %d %d %d\n", i, sino_dih[i], angle_dih[i], atom1_dih[i], atom2_dih[i], atom3_dih[i], atom4_dih[i]);
        }

        for (int i = 0; i < ndihedrals; ++i)
        {
            printf("test2: i: %d ==> %d %f %d %d %d %d\n", i, sino_dih[i], angle_dih[i], atom1_dih[i], atom2_dih[i], atom3_dih[i], atom4_dih[i]);
        }

这是第一个 for 循环的输出:(还有更多行,我只是显示两个 for 循环的前几行输出。我通过将 sleep(1); 语句放在 printf 之后得到这些)

i: 0 ==> 1 -46.265598 696 698 699 700
i: 1 ==> 2 176.755005 696 698 699 701
i: 2 ==> 3 -56.561798 698 699 701 702
i: 3 ==> 4 168.240997 700 699 701 702
i: 4 ==> 5 172.516998 699 701 702 703
i: 5 ==> 6 -69.096497 699 701 702 704
i: 6 ==> 7 143.464005 701 702 704 705
i: 7 ==> 8 -98.824898 703 702 704 705
i: 8 ==> 9 149.878998 702 704 705 706
i: 9 ==> 10 -70.438004 702 704 705 707
i: 10 ==> 11 122.935997 704 705 707 708

这是第二个 for 循环的输出:

test2: i: 0 ==> 1 0.000000 4533 4440 4441 4443
test2: i: 1 ==> 2 0.000000 4534 4442 4441 4443
test2: i: 2 ==> 3 0.000000 4535 4441 4443 4444
test2: i: 3 ==> 4 0.000000 4536 4441 4443 4444
test2: i: 4 ==> 5 0.000000 4537 632 633 635
test2: i: 5 ==> 6 0.000000 4538 634 633 635
test2: i: 6 ==> 7 0.000000 4539 633 635 636
test2: i: 7 ==> 8 0.000000 4540 633 635 636
test2: i: 8 ==> 9 0.000000 4541 635 636 638
test2: i: 9 ==> 10 0.000000 4542 637 636 638
test2: i: 10 ==> 11 0.000000 4543 636 638 639

这是代码的声明部分,我尝试了使用 malloc 和 calloc 的代码。

        sino_dih = (int *) calloc (natoms, sizeof (int));
        atom1_dih = (int *) calloc (natoms, sizeof (int));
        atom2_dih = (int *) calloc (natoms, sizeof (int));
        atom3_dih = (int *) calloc (natoms, sizeof (int));
        atom4_dih = (int *) calloc (natoms, sizeof (int));
        angle_dih = (float *) calloc (natoms, sizeof (float));

我已在此处附上完整代码(链接:https://wetransfer.com/downloads/06c55057ecb6dade8af6407addadec6920180419090057/585c26)

My GCC version: 7.3.1 20180312

最佳答案

数组的大小是 natoms ,但您正在访问元素 0 ..ndihedrals-1 。如果natoms < ndihedrals将会出现未定义的行为。 我想你应该分配 ndihedrals许多元素,例如

sino_dih = calloc(ndihedrals, sizeof(int));
atom1_dih = ...
...

(我必须阅读完整的代码才能得出这个结论)

关于c - gcc 数组中的值不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49916974/

相关文章:

c - 在 c 中读取文件后,我的打印函数中出现了错误

c - sendmsg() 函数内部做什么?

c - gcc 优化掉复合语句

c - 如何定义此代码并将其作为函数调用?

php - 在多维数组中搜索值并在 PHP 中获取父数组

php - 在多维数组中移动

macos - Mac OS X ld : library not found for -lpython3

c++ - 如何更改automake的CXXLINK中的顺序?

sql - 更新 PostgreSQL 数组中的值

c - *.hxx 中声明的 void 函数,在 *.cxx 中定义但在 *.c 中未定义