C pointer to two dimensional array -
C pointer to two dimensional array -
i know there several questions gives (and working) solutions, none imho says best way accomplish this. so, suppose have 2d array :
int tab1[100][280];
we want create pointer points 2d array. accomplish this, can :
int (*pointer)[280]; // pointer creation pointer = tab1; //assignation pointer[5][12] = 517; // utilize int myint = pointer[5][12]; // utilize
or, alternatively :
int (*pointer)[100][280]; // pointer creation pointer = &tab1; //assignation (*pointer)[5][12] = 517; // utilize int myint = (*pointer)[5][12]; // utilize
ok, both seems work well. know :
what best way, 1st or 2nd ? are both equals compiler ? (speed, perf...) is 1 of these solutions eating more memory other ? what more used developers ? //defines array of 280 pointers (1120 or 2240 bytes) int *pointer1 [280]; //defines pointer (4 or 8 bytes depending on 32/64 bits platform) int (*pointer2)[280]; //pointer array of 280 integers int (*pointer3)[100][280]; //pointer 2d array of 100*280 integers
using pointer2
or pointer3
produce same binary except manipulations ++pointer2
pointed out whozcraig.
i recommend using typedef
(producing same binary code above pointer3
)
typedef int mytype[100][280]; mytype *pointer3;
note: since c++11, can utilize keyword using
instead of typedef
using mytype = int[100][280]; mytype *pointer3;
in example:
mytype *pointer; // pointer creation pointer = &tab1; // assignation (*pointer)[5][12] = 517; // set (write) int myint = (*pointer)[5][12]; // (read)
note: if array tab1
used within function body => array placed within phone call stack memory. stack size limited. using arrays bigger free memory stack produces stack overflow crash.
the total snippet online-compilable @ gcc.godbolt.org
int main() { //defines array of 280 pointers (1120 or 2240 bytes) int *pointer1 [280]; static_assert( sizeof(pointer1) == 2240, "" ); //defines pointer (4 or 8 bytes depending on 32/64 bits platform) int (*pointer2)[280]; //pointer array of 280 integers int (*pointer3)[100][280]; //pointer 2d array of 100*280 integers static_assert( sizeof(pointer2) == 8, "" ); static_assert( sizeof(pointer3) == 8, "" ); // utilize 'typedef' (or 'using' if utilize modern c++ compiler) typedef int mytype[100][280]; //using mytype = int[100][280]; int tab1[100][280]; mytype *pointer; // pointer creation pointer = &tab1; // assignation (*pointer)[5][12] = 517; // set (write) int myint = (*pointer)[5][12]; // (read) homecoming myint; }
c arrays pointers
Comments
Post a Comment