C ++ Global Array Distribution

I have a global multidimensional C ++ array with static linking. I assume that a stack will be allocated (I cannot find the corresponding section in the standard). Does it stand out contiguously?

Another question: I want to convert these static global n-dimensional arrays to be heaped. What is the easiest way, given that I want to minimize code changes? I can think of converting arrays to n-dimensional pointers and malloc'ing at the beginning of the main and freeing before exiting main. But I have to worry about contiguous distribution. Does anyone see a better way?

Thank,

Nilesh.

+3
source share
3 answers

++ . , ( ).

; . , .

, ( "" ), , ; globals , main() main().

?

, , . (: 1-D, , up- "".) , , . , , .

n- , . , , ?

. . (, std::vector, .)

n-

. - , , , , . , , 1- , N-D .

malloc'ing .

, , free , valgrind . OS , .

, - :

#include <stddef.h>

static const size_t kDimX = 5;
static const size_t kDimY = 20;
static const size_t kDimZ = 4;

inline size_t DimsToVector(size_t x, size_t y, size_t z)
{
    return (x * kDimY + y) * kDimZ + z;
}

float* data = 0;

int main()
{
    data = new float[kDimX * kDimY * kDimZ];

    // Read elements with: data[DimsToVector(x, y, z)]
    // Write v with: data[DimsToVector(x, y, z)] = k;

    delete[] data; // Optional.
}

, , Boost, operator [], , .

+2

. .

"", , , , , typedef .

typedef int TenIntegers[10];
TenIntegers* ints;

int main()
{
    ints = new TenIntegers[50];

    // your code here
    ints[0][5] = 3;

    delete[] ints;
}
+1

1) The memory for the globals is allocated somewhere "in memory". It is neither on the stack nor on the heap. For example, global constants are usually placed in a read-only section of an executable file. Strictly speaking, it is implementation dependent. Why do you need to know this?

2) The memory will be continuous.

0
source

All Articles