Created
April 27, 2017 14:21
-
-
Save lebedov/1bea63c6772d53605d6dcb3d5551d739 to your computer and use it in GitHub Desktop.
How to save a 2D array of pointers to a class attribute and access the array's contents properly.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// How to save a 2D array of pointers to a class attribute and | |
// access the array's contents properly. | |
#include <iostream> | |
#include <stdio.h> | |
// Show pointer values in array: | |
void show_ptr(int *a[2][2]) { | |
for (int i=0; i<2; i++) { | |
for (int j=0; j<2; j++) { | |
printf("[%d,%d] %p\n", i, j, &a[i][j]); | |
} | |
} | |
} | |
// Cast for converting void pointer to 2D array of pointers: | |
#define ARRAY(x) ((int *(*)[2])x) | |
class Foo { | |
public: | |
Foo(int *a[2][2]) {this->a = a;}; | |
void set(int v) { | |
for (int i=0; i<2; i++) { | |
for (int j=0; j<2; j++) { | |
for (int k=0; k<2; k++) { | |
ARRAY(a)[i][j][k] = v; | |
} | |
} | |
} | |
}; | |
private: | |
void *a; | |
}; | |
// Show array contents: | |
void show(int *a[2][2]) { | |
for (int i=0; i<2; i++) { | |
for (int j=0; j<2; j++) { | |
std::cout << "[" << i << "," << j << "] "; | |
for (int k=0; k<2; k++) { | |
std::cout << a[i][j][k] << " "; | |
} | |
std::cout << std::endl; | |
} | |
} | |
} | |
int main(void) { | |
int *data[2][2]; | |
for (int i=0; i<2; i++) { | |
for (int j=0; j<2; j++) { | |
data[i][j] = (int *)malloc(2*sizeof(int)); | |
} | |
} | |
Foo f = Foo(data); | |
f.set(0); | |
show(data); | |
f.set(1); | |
show(data); | |
for (int i=0; i<2; i++) { | |
for (int j=0; j<2; j++) { | |
free(data[i][j]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment