Is there any way to malloc a large array, but refer to it with 2D syntax? I want something like:
int *memory = (int *)malloc(sizeof(int)*400*200);
int MAGICVAR = ...;
MAGICVAR[20][10] = 3; //sets the (200*20 + 10)th element
#define INDX(a,b) (a*200+b);
and then refer to my blob like:
memory[INDX(a,b)];
I'd much prefer:
memory[a][b];
int *MAGICVAR[][200] = memory;
Does no syntax like this exist? Note the reason I don't just use a fixed width array is that it is too big to place on the stack.
void toldyou(char MAGICVAR[][286][5]) {
//use MAGICVAR
}
//from another function:
char *memory = (char *)malloc(sizeof(char)*1820*286*5);
fool(memory);
I get a warning, passing arg 1 of toldyou from incompatible pointer type
, but the code works, and I've verified that the same locations are accessed. Is there any way to do this without using another function?
The basic form of declaring a two-dimensional array of size x, y: Syntax: data_type array_name[x][y]; Here, data_type is the type of data to be stored.
Data in multidimensional arrays are stored in tabular form (in row major order). Syntax: data_type[1st dimension][2nd dimension][].. [Nth dimension] array_name = new data_type[size1][size2]….
A 2D array can be dynamically allocated in C using a single pointer. This means that a memory block of size row*column*dataTypeSize is allocated using malloc and pointer arithmetic can be used to access the matrix elements.
In C programming, you can create an array of arrays. These arrays are known as multidimensional arrays. For example, float x[3][4];
Yes, you can do this, and no, you don't need another array of pointers like most of the other answers are telling you. The invocation you want is just:
int (*MAGICVAR)[200] = malloc(400 * sizeof *MAGICVAR);
MAGICVAR[20][10] = 3; // sets the (200*20 + 10)th element
If you wish to declare a function returning such a pointer, you can either do it like this:
int (*func(void))[200]
{
int (*MAGICVAR)[200] = malloc(400 * sizeof *MAGICVAR);
MAGICVAR[20][10] = 3;
return MAGICVAR;
}
Or use a typedef, which makes it a bit clearer:
typedef int (*arrayptr)[200];
arrayptr function(void)
{
/* ... */
Use a pointer to arrays:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int (*arr)[10];
arr = malloc(10*10*sizeof(int));
for (int i = 0; i < 10; i++)
for(int j = 0; j < 10; j++)
arr[i][j] = i*j;
for (int i = 0; i < 10; i++)
for(int j = 0; j < 10; j++)
printf("%d\n", arr[i][j]);
free(arr);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With