惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Martin Fowler
Martin Fowler
D
DataBreaches.Net
F
Fortinet All Blogs
阮一峰的网络日志
阮一峰的网络日志
博客园_首页
Apple Machine Learning Research
Apple Machine Learning Research
H
Help Net Security
M
MIT News - Artificial intelligence
美团技术团队
人人都是产品经理
人人都是产品经理
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The Cloudflare Blog
有赞技术团队
有赞技术团队
L
LangChain Blog
博客园 - Franky
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 【当耐特】
S
SegmentFault 最新的问题
V
Visual Studio Blog
Blog — PlanetScale
Blog — PlanetScale
Hugging Face - Blog
Hugging Face - Blog
B
Blog
I
InfoQ

Yusuf Aytas

When Code Is Cheap, Does Quality Still Matter? Why Crouching Tiger, Hidden Dragon Is a Masterpiece Why We Ignore Advice The Mirror Is Part of the Machine When Too Many Maps Overlap on One Person The Work Runs on Different Maps Your Work Introduces You Trial By Fire The Dude Why Headcount Math Lies Capacity Is the Roadmap The Roadmap Is Not the System Torres del Paine W Trek Escaping Status Theater Incentives Drive Everything Scaling Culture Without Dilution What Good Looks Like Why Airport Security Feels Random Why Politics Appear How to Work with Me The Janus Protocol Multi-Horizon Delivery Framework What Good Execution Looks Like Managing Your Manager Why Kingdom of Heaven’s Director’s Cut Is Better AI Broke Interviews Most of What We Call Progress Managers Have Been Vibe Coding All Along Stop Wasting Brainpower Why Over-Engineering Happens
Heap-Allocated 2D Structures in C++
Yusuf Aytas · 2008-10-15 · via Yusuf Aytas

Published · 2 min read

C++ öğrenirken en çok zorlanılan konulardan biri, işin mutfağı olan manuel bellek yönetimi ve pointer yapılarıdır. Bugün çoğu modern dil bizim için bellekle ilgilense de, C++ hâlâ düşük seviye kontrolün ne anlama geldiğini öğretmek için altın standarttır. Özellikle çift pointer (int**) kullanarak 2D dinamik dizi oluşturmak, bilgisayar biliminde veri yapılarının bellek üzerinde gerçekte nasıl tutulduğunu anlamamızı sağlar.

Bu örnekte:

  • stack üzerinde değil, heap üzerinde dinamik bir 2D dizi oluşturuyoruz,
  • her satır için ayrı bellek alanı ayırıyoruz,
  • elemanları dolduruyoruz,
  • bir fonksiyon aracılığıyla diziyi işliyoruz,
  • ve en önemlisi, ayırdığımız belleği doğru şekilde serbest bırakıyoruz.

Bu, C++’ta bellek yönetimini anlamanın temel taşıdır:
Belleği sen ayırırsın, sen doldurursun, sen temizlersin.

Aşağıdaki kod, pointer mantığını, dinamik bellek tahsisini ve 2D veri yapılarının düşük seviyede nasıl işlendiğini gösteren sade ama çok öğretici bir örnektir.

#include <iostream>

using namespace std;

void printElements(int **haha, int size1, int size2);

int main() {
    // Initialize the array sizes
    const int size1 = 4, size2 = 3;

    // Define a pointer to a pointer (for a 2D array)
    int **ptr;

    // Initialize the 2D array
    ptr = new int*[size1];
    for (int i = 0; i < size1; ++i) {
        ptr[i] = new int[size2];
    }

    // Assign values to the 2D array and print them
    for (int i = 0; i < size1; ++i) {
        for (int j = 0; j < size2; ++j) {
            ptr[i][j] = i + j;  // Example assignment
        }
    }

    // Print the elements using the function
    printElements(ptr, size1, size2);

    // Deallocate memory
    for (int i = 0; i < size1; ++i) {
        delete[] ptr[i];
    }
    delete[] ptr;

    return 0;
}

void printElements(int **haha, int size1, int size2) {
    cout << "Elements in the array:" << endl;
    for (int i = 0; i < size1; ++i) {
        for (int j = 0; j < size2; ++j) {
            cout << haha[i][j] << " ";
        }
        cout << endl;
    }
}