Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
Last active February 19, 2016 00:08
Show Gist options
  • Save DmitrySoshnikov/08dfce7978bc6ff09aae to your computer and use it in GitHub Desktop.
Save DmitrySoshnikov/08dfce7978bc6ff09aae to your computer and use it in GitHub Desktop.
Contiguous and non-contiguous C-arrays allocation
/**
* 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