Can a pointer to a multidimensional array in C be written simply as:
double *array;
Where array
is an n by n matrix?
And then can I access the element in row i
, column j
, by array[i][j]
?
Or is there such thing as a double pointer?
Can a pointer to a multidimensional array in C be written simply as:
double *array;
Where array
is an n by n matrix?
And then can I access the element in row i
, column j
, by array[i][j]
?
Or is there such thing as a double pointer?
Can a pointer to a multidimensional array in C be written simply as:
double *array;
Yes.
Say you have M x N
array. You can use:
double* array = malloc(M*N*sizeof(*array));
Then, you can access the elements by using:
size_t getArrayIndex(size_t m, size_t n, size_t M)
{
return (m*M+n);
}
double getArrayElement(double* array, size_t m, size_t n, size_t M)
{
return array[getArrayIndex(m, n, M)];
}
double *
is a pointer to a double
. It's also pointer to an element of an array of double
.
To do what you want:
double bla[23][42]; // array of arrays, type is double [23][42]
double (*p)[23][42] = &bla; // pointer to an object of type double [23][42]
to make a pointer to a multidimensional array array[i][j]
where i is number of rows and j is number columns you can do double (*ptr)[j]
which says that ptr is a pointer to double array of j elements. then you can assign ptr=array;
Can a pointer to a multidimensional array in C be written simply as:
double *array;
That could be something that is used to represent an array, when handing it over to a function! A C array is then only represented by a pointer to its first element. How these elements are organized internally is up to you; making sure you don't use indices that are actually outside the array, too.
Or is there such thing as a double pointer?
Of course; double ***ndim_array
is perfectly valid. However, you could also use multidimensional arrays like double [][][]
.
(Thanks to all the contributors in comments!)