cpp:dynamic_memory

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision Both sides next revision
cpp:dynamic_memory [2017/04/11 10:20]
gthanos [Έλεγχος δέσμευσης μνήμης]
cpp:dynamic_memory [2017/06/08 06:22]
gthanos
Line 80: Line 80:
 </code> </code>
  
 +===== Παράδειγμα δέσμευσης μνήμης για την αρχικοποίηση ενός διδιάστατου πίνακα =====
 +
 +<code cpp dynamicMemory2D.cpp>
 +#include <iostream>
 +#include <stdlib.h>
 +
 +using namespace std;
 +
 +int main(int argc, char *argv[]) {
 +  int **array2d, rows, columns;
 +  
 +  cout << "Enter number of rows: ";
 +  cin >> rows;
 +  
 +  cout << "Enter number of columns: ";
 +  cin >> columns;
 +  
 +  array2d = new (nothrow) int*[rows];
 +  if(array2d == NULL) {
 +    cerr < "Memory allocation error!\n";
 +    return -1;
 +  }
 +  for(int i=0; i<rows; i++) {
 +    array2d[i] = new (nothrow) int[columns];
 +    if(array2d[i] == NULL) {
 +      cerr < "Memory allocation error!\n";
 +      return -1;
 +    }
 +  }
 +  
 +  for(int i=0; i<rows; i++) {
 +    for(int j=0; j<columns; j++) {
 +      array2d[i][j] = i+j;
 +      cout << array2d[i][j] << "  ";
 +    }
 +    cout << endl;
 +  }
 +  
 +  for(int i=0; i<rows; i++) 
 +    delete[] array2d[i];
 +  delete[] array2d;
 +}
 +</code>
  
  
cpp/dynamic_memory.txt · Last modified: 2021/04/27 05:01 (external edit)