c++ - 犯一个愚蠢的内存错误

标签 c++ memory-leaks

<分区>

我已经有一段时间没有使用 C++ 了,我似乎犯了一个我确信是非常愚蠢的错误。谁能告诉我为什么

#include <cstdio>
#include <cstdlib>
#include <iostream>

using namespace std;

int main() {
        double* atoms;

        atoms = (double*)malloc(10 * 3*sizeof(double));
        for (int i = 0; i < 10; i++) {
                for (int j = 0; j < 3; j++) {
                        atoms[i*10 + j] = 2.0;
                }
        }

        for (int i = 0; i < 10; i++) {
                for (int j = 0; j < 3; j++) {
                        cout << atoms[i*10 + j] << endl;
                }
                cout << endl;
        }


        free(atoms);

        return 0;
}

正在打印

2
2
2

2
2
2

2
2
2

6.94528e-310
6.94528e-310
0

0
4.24399e-314
4.24399e-314

2
2
2

2
2
2

2
2
2

2
2
2

2
2
2

而不是全 2?谢谢

最佳答案

    for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 3; j++) {
                    atoms[i*10 + j] = 2.0;

我猜,你想写:

    for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 3; j++) {
                    atoms[j*10 + i] = 2.0; 

你在两个循环中都有同样的错误,确切地说,我认为这是显而易见的:)

关于c++ - 犯一个愚蠢的内存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14722819/

相关文章:

c++ - 如何创建n维测试数据进行聚类分析?

android - LeakCanary 与 Cordova 的依赖关系 - 找不到方法 debugCompile()

c++ - 函数调用无法正常工作

javascript - 为什么这个 javascript 会因内存使用而导致浏览器崩溃?

c# - 清理非托管代码中的内存泄漏

qt - 如何解决 QPixmap::fromImage 内存泄漏?

c - 我的 sqlite3 c 函数正在泄漏内存

c++ - #if 预处理器指令可以嵌套在 C++ 中吗?

python - 如何通过 C++ 在 Python 函数中传递字符串参数

c++ - 如何在 Windows 上将 BYTE 数组映射为 FILE *