Reputation: 31
I am trying to solve the following issue but could not succeed yet:
I have a two-diwmensional array of pointers:
int* a[16][128];
Now I want to make a pointer to this array in that way that I can use pointer arithmetic on it. Thus, something like this:
ptr = a;
if( ptr[6][4] == NULL )
ptr[6][4] = another_ptr_to_int;
I tried already some variations but it either fails then on the first line or on the if condition.
So, how can it be solved? I would like to avoid template classes etc. Code is for a time critical part of an embedded application, and memory is very limited. Thus, I would like ptr
to be only sizeof(int*)
bytes long.
Upvotes: 0
Views: 639
Reputation: 308
To start with array pointer basics for a 1D array, [tutorialspoint][1] has a very easy to ready description. From their example:
#include <stdio.h>
int main () {
/* an array with 5 elements */
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
int i;
p = balance; //Here the pointer is assign to the start of the array
/* output each array element's value */
printf( "Array values using pointer\n");
for ( i = 0; i < 5; i++ ) {
printf("*(p + %d) : %f\n", i, *(p + i) );
}
printf( "Array values using balance as address\n");
for ( i = 0; i < 5; i++ ) {
printf("*(balance + %d) : %f\n", i, *(balance + i) ); // Note the post increment
}
return 0;
}
There are a couple of relavent Stack overflow answers that describe 2D arrays: How to use pointer expressions to access elements of a two-dimensional array in C?
Pointer-to-pointer dynamic two-dimensional array
how to assign two dimensional array to **pointer ?
Representing a two-dimensional array assignment as a pointer math?
[1]: https://www.tutorialspoint.com/cprogramming/c_pointer_to_an_array.htm
Upvotes: 0
Reputation: 13589
Thing you seem to want:
int* (*ptr)[128] = a;
Actual pointer to the array:
int* (*ptr)[16][128] = &a;
Upvotes: 1
Reputation: 66459
A pointer to the first element of the array (which is what you want) could be declared as
int* (*ptr)[128];
A pointer to the array itself would be
int* (*ptr)[16][128];
and is not what you're looking for.
Upvotes: 2