Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Saturday, January 9, 2016

Create a pointer to two-dimensional array

Create a pointer to two-dimensional array


I need a pointer to a static 2-dimensional array. How is this done?

static uint8_t l_matrix[10][20];    void test(){     uint8_t **matrix_ptr = l_matrix; //wrong idea   }  

I get all kinds of errors like:

  • warning: assignment from incompatible pointer type
  • subscripted value is neither array nor pointer
  • error: invalid use of flexible array member

Answer by Nick Dandoulakis for Create a pointer to two-dimensional array


You can do it like this:

uint8_t (*matrix_ptr)[10][20] = &l_matrix;  

Answer by gnosis for Create a pointer to two-dimensional array


You can always avoid fiddling around with the compiler by declaring the array as linear and doing the (row,col) to array index calculation by yourself.

static uint8_t l_matrix[200];    void test(int row, int col, uint8_t val)    {       uint8_t* matrix_ptr = l_matrix;     matrix_ptr [col+y*row] = val; // to assign a value    }  

this is what the compiler would have done anyway.

Answer by Johannes Schaub - litb for Create a pointer to two-dimensional array


Here you wanna make a pointer to the first element of the array

uint8_t (*matrix_ptr)[20] = l_matrix;  

With typedef, this looks cleaner

typedef uint8_t array_of_20_uint8_t[20];  array_of_20_uint8_t *matrix_ptr = l_matrix;  

Then you can enjoy life again :)

matrix_ptr[0][1] = ...;  

Beware of the pointer/array world in C, much confusion is around this.


Edit

Reviewing some of the other answers here, because the comment fields are too short to do there. Multiple alternatives were proposed, but it wasn't shown how they behave. Here is how they do

uint8_t (*matrix_ptr)[][20] = l_matrix;  

If you fix the error and add the address-of operator & like in the following snippet

uint8_t (*matrix_ptr)[][20] = &l_matrix;  

Then that one creates a pointer to an incomplete array type of elements of type array of 20 uint8_t. Because the pointer is to an array of arrays, you have to access it with

(*matrix_ptr)[0][1] = ...;  

And because it's a pointer to an incomplete array, you cannot do as a shortcut

matrix_ptr[0][0][1] = ...;  

Because indexing requires the element type's size to be known (indexing implies an addition of an integer to the pointer, so it won't work with incomplete types). Note that this only works in C, because T[] and T[N] are compatible types. C++ does not have a concept of compatible types, and so it will reject that code, because T[] and T[10] are different types.


The following alternative doesn't work at all, because the element type of the array, when you view it as a one-dimensional array, is not uint8_t, but uint8_t[20]

uint8_t *matrix_ptr = l_matrix; // fail  


The following is a good alternative

uint8_t (*matrix_ptr)[10][20] = &l_matrix;  

You access it with

(*matrix_ptr)[0][1] = ...;  matrix_ptr[0][0][1] = ...; // also possible now  

It has the benefit that it preserves the outer dimension's size. So you can apply sizeof on it

sizeof (*matrix_ptr) == sizeof(uint8_t) * 10 * 20  


There is one other answer that makes use of the fact that items in an array are contiguously stored

uint8_t *matrix_ptr = l_matrix[0];  

Now, that formally only allows you to access the elements of the first element of the two dimensional array. That is, the following condition hold

matrix_ptr[0] = ...; // valid  matrix_ptr[19] = ...; // valid    matrix_ptr[20] = ...; // undefined behavior  matrix_ptr[10*20-1] = ...; // undefined behavior  

You will notice it probably works up to 10*20-1, but if you throw on alias analysis and other aggressive optimizations, some compiler could make an assumption that may break that code. Having said that, i've never encountered a compiler that fails on it (but then again, i've not used that technique in real code), and even the C FAQ has that technique contained (with a warning about its UB'ness), and if you cannot change the array type, this is a last option to save you :)

Answer by Rob Wells for Create a pointer to two-dimensional array


G'day,

The declaration

static uint8_t l_matrix[10][20];  

has set aside storage for 10 rows of 20 unit8_t locations, i.e. 200 uint8_t sized locations, with each element being found by calculating 20 x row + column.

So doesn't

uint8_t (*matrix_ptr)[][20] = l_matrix;  

give you what you need and point to the column zero element of the first row of the array?

Edit: Thinking about this a bit further, isn't an array name, by definition, a pointer? That is, the name of an array is a synonym for the location of the first element, i.e. l_matrix[0][0]?

Edit2: As mentioned by others, the comment space is a bit too small for further discussion. Anyway:

typedef uint8_t array_of_20_uint8_t[20];  array_of_20_uint8_t *matrix_ptr = l_matrix;  

does not provide any allocation of storage for the array in question.

As mentioned above, and as defined by the standard, the statement:

static uint8_t l_matrix[10][20];  

has set aside 200 sequential locations of type uint8_t.

Referring to l_matrix using statements of the form:

(*l_matrix + (20 x rowno) + colno)  

will give you the contents of the colno'th element found in row rowno.

All pointer manipulations automatically take into account the size of the object pointed to. - K&R Section 5.4, p.103

This is also the case if any padding, or byte alignment shifting. is involved in the storage of the object at hand. The compiler will automatically adjust for these. By definition of the C ANSI standard.

HTH

cheers,

Answer by Ken Keenan for Create a pointer to two-dimensional array


You want a pointer to the first element, so;

static uint8_t l_matrix[10][20];    void test(){     uint8_t *matrix_ptr = l_matrix[0]; //wrong idea   }  

Answer by Georg Schlly for Create a pointer to two-dimensional array


class="descans">

Instead of

static uint8_t l_matrix[10][20];  uint8_t **matrix_ptr = l_matrix; //wrong idea  

use

uint8_t *matrix_ptr = l_matrix;  

Multi-dimensional arrays in C are in truth only 1-dimensional.

Answer by Stan Graves for Create a pointer to two-dimensional array


In the general case, a pointer to an 2-D array is declared like this:

int ***matrix_ptr = &l_matrix;  

Pointer definitions are resolved from the "inside out" - or the notation that is closest to the variable name, and getting farther away with each step. From left to right:

The third "" is the "pointer". The second "" is for the first dimension of the array. The first "" is for the second dimension of the array.
You can continue to add "
" for any additional dimensions you want to add to the array.

It is not necessary to know the dimensions of the array in order to declare the pointer to that array.

The [] notation is syntactic sugar for the calculation of array offsets, but it is nice sugar:

matrix_ptr[0][1] = ...;  

There is no requirement that the second dimension of the 2-D matrix have the same number of elements at every position.

Answer by Sagar for Create a pointer to two-dimensional array


In

int *ptr= l_matrix[0];  

you can access like

*p  *(p+1)  *(p+2)  

after all 2 dimensional arrays are also stored as 1-d.

Answer by Kornel for Create a pointer to two-dimensional array


In C99 (supported by clang and gcc) there's an obscure syntax for passing fixed-size arrays to functions by reference:

static int l_matrix[10][20];    void test(int matrix_ptr[static 10][20]) {  }    int main(void) {      test(l_matrix);  }  

Unlike a pointer, this preserves information about array size, theoretically allowing compiler to warn about passing too-small array and spot obvious out of bounds access.

Sadly, it doesn't fix sizeof() and compilers don't seem to use that information yet, so it remains a curiosity.

Answer by mathengineer for Create a pointer to two-dimensional array


This is not elegant but work better than many others:

#include "stdafx.h"  #include   #define DIM 3  #define WORMS 50000 //gusanos    void halla_centros_V000(double CENW[][DIM])  {      int w,i;      for (w=0;w

Answer by Super Cat for Create a pointer to two-dimensional array


To fully understand this, you must grasp the following concepts:

Arrays are not pointers!

First of all (And it's been preached enough), arrays are not pointers. Instead, in most uses, they 'decay' to the adress to their first element, which can be assigned to a pointer:

int a[] = {1, 2, 3};    int *p = a; // p now points to a[0]  

I assume it works this way so that the array's contents can be accessed without copying all of them. That's just a behavior of array types and is not meant to imply that they are same thing.



Multidimensional arrays

Multidimensional arrays are just a way to 'partion' memory in a way that the compiler/machine can understand and operate on.

For instance, int a[4][3][5] = an array containing 4*3*5 (60) 'chunks' of interger-sized memory.

The advantage over using int a[4][3][5] vs plain int b[60] is that they're now 'partioned' (Easier to work with their 'chunks', if needed), and the program can now perform bound checking.

In fact, int a[4][3][5] is stored exactly like int b[60] in memory - The only difference is that the program now manages it as if they're seperate entities of certain sizes (Specifically, four groups of three groups of five).

Keep in mind: Both int a[4][3][5] and int b[60] are the same in memory, and the only difference is how they're handled by the application/compiler

{    {1, 2, 3, 4, 5}    {6, 7, 8, 9, 10}    {11, 12, 13, 14, 15}  }  {    {16, 17, 18, 19, 20}    {21, 22, 23, 24, 25}    {26, 27, 28, 29, 30}  }  {    {31, 32, 33, 34, 35}    {36, 37, 38, 39, 40}    {41, 42, 43, 44, 45}  }  {    {46, 47, 48, 49, 50}    {51, 52, 53, 54, 55}    {56, 57, 58, 59, 60}  }  

From this, you can clearly see that each "partion" is just an array that the program keeps track of.



Syntax

Now, arrays are synatically different from pointers. Specifically, this means the compiler/machine will treat them differently. This may seem like a no brainer, but take a look at this:

int a[3][3];    printf("%p %p", a, &(a[0]));  

The above example prints the same memory address twice, like this:

0x7eb5a3b4 0x7eb5a3b4  

However, only one can be assigned to a pointer so directly:

int *p1 = &(a[0]); // RIGHT !    int *p2 = a; // WRONG !  

Why can't a be assigned to a pointer but &(a[0]) can?

This, simply, is a consequnce of multidimensional arrays, and I'll explain why:

At the level of 'a', we still see that we have another 'dimension' to look forward to. At the level of '&(a[0])', however, we're already in the top dimension, so as far as the program is concerned we're just looking at a normal array.

You may be asking:

Why does it matter if the array is multidimensional in regards to making a pointer for it?

It's best to think this way:

A 'decay' from a multidimensional array is not just an address, but an address with partion data (AKA it still understands that it's underlying data is made of other arrays), which consists of boundaries set by the array beyond the first dimension.

This 'partion' logic cannot exist within a pointer unless we specify it:

int a[4][5][95][8];    int (*p)[5][95][8];    p = a;  

Note the use of parenthesis around *p: int (*p)[5][95][8] - That's to specify that we're making a pointer with these bound, not an array of pointers with these bounds: int *p[5][95][8]



Conclusion

Let's review:

  • Arrays decay to addresses if they have no other purpose in the used context
  • Multidimensional arrays are just arrays of arrays - Hence, the 'decayed' address will carry the burden of "I have sub dimensions"
  • Dimension data cannot exist in a pointer unles you give it to it.

I feel as though this is a rough draft, so expect some editorial work soon.


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

Related Posts:

0 comments:

Post a Comment

Popular Posts

Fun Page

Powered by Blogger.