Last active
February 19, 2016 00:08
-
-
Save DmitrySoshnikov/08dfce7978bc6ff09aae to your computer and use it in GitHub Desktop.
Contiguous and non-contiguous C-arrays allocation
This file contains hidden or 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
/** | |
* Contiguous and non-contiguous C-arrays allocation in memory. | |
* by Dmitry Soshnikov <[email protected]> | |
*/ | |
#include <iostream> | |
int main() | |
{ | |
// ----------------------------- | |
// 1. Contiguous allocation. | |
// | |
// Notice, that foo[1][2] may require only one | |
// memory access in generated code: | |
// | |
// Mem[foo + 12 * row + 4 * col] | |
// | |
// (where 12 bytes is assuming 32-bit architecture | |
// for 3 ints, 4 bytes each) | |
int foo[3][3] = { | |
{1, 2, 3}, | |
{4, 5, 6}, | |
{7, 8, 9} | |
}; | |
std::cout << foo[1][2]; // 6 | |
std::cout << foo[2][-1]; // 6 | |
std::cout << foo[0][5]; // 6 | |
std::cout << *(*(foo + 2) - 1); // 6 | |
// ----------------------------- | |
// 2. Non-contiguous allocation. | |
// | |
// And here in contrast, bar[1][2] requires two | |
// memory accesses in generated code: | |
// | |
// Mem[Mem[bar + 4 * row] + 4 * col] | |
int one[3] = {1, 2, 3}; | |
int two[3] = {4, 5, 6}; | |
int three[3] = {7, 8, 9}; | |
// Looks "the same", but actually not. | |
int* bar[3] = { | |
one, | |
two, | |
three | |
}; | |
std::cout << bar[1][2]; // 6, still guaranteed | |
std::cout << bar[2][-1]; // ? | |
std::cout << bar[0][5]; // ? | |
std::cout << *(*(bar + 2) - 1); // ? | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment