0

I have the following code in C where G is a global variable:

long *G;

int function(long matrix[35][10]){
    G=&matrix[0][0];
}

Once I store the address of matrix[0][0] in G, I can access all the elements of matrix like so:

G[0]=...
G[1]=...
.
.
.
G[349]=...

I want to be able to access all of these elements similar to how I can with matrix, by using the two square brackets from inside of another function. How would I be able to do that? That is, how can I tell the compiler that the offset for the second dimension in this 2 dimensional array is 10?


I did look at this answer: Create a pointer to two-dimensional array , but I'm not sure if the user asked the exact same thing. Please correct me if I'm wrong

Community
  • 1
  • 1

2 Answers2

2
long (*array)[10] = (long(*)[10])G;  

array is a pointer to an array of 10 longs.

jfly
  • 7,715
  • 3
  • 35
  • 65
  • Just to make sure, only 64 bits are allocated for `array` right? The fact that there is a 3 in front of it, makes me think three longs are allocated – user3427787 Mar 17 '14 at 07:07
  • It depends on the system, `sizeof(long*)` will be allocated for `array`. – jfly Mar 17 '14 at 07:15
  • 2
    Or since he wants to use `G` itself like that, rather just declare `G` as `long (* G)[10];` and assign `matrix` to it directly, like `G = matrix;`. – Utkan Gezer Mar 17 '14 at 07:44
-2

Make G a poiter to pointer.

long **G;

Still you will not be able to access directly by G[i] i goes from 0 to 349.

But one easy thing that you can do is converting a number to 2 subscripts.

for example:

G[349] is actually G[34][9].

Hence formula is if you want

G[k]

then access it like this:

G[k/10][k%10];

This is for this particular case.

For general case, the formula to convert 1 subscript to 2 subscripts is:

G[k] is equivalent to G[k/NO_OF_COLUMNS][k%NO_OF_COLUMNS];
Bhavesh Munot
  • 675
  • 1
  • 6
  • 13
  • 1
    this does not work. pointers and arrays are not the same. reading G[34] will get an element from the data buffer of the array and will try to dereference it that obviously causes an access violation – vlad_tepesch Mar 17 '14 at 08:34