Cla*_*diu 13 c arrays malloc pointers multidimensional-array
有没有什么方法可以对大型数组进行malloc,但是用2D语法引用它?我想要的东西:
int *memory = (int *)malloc(sizeof(int)*400*200);
int MAGICVAR = ...;
MAGICVAR[20][10] = 3; //sets the (200*20 + 10)th element
Run Code Online (Sandbox Code Playgroud)
#define INDX(a,b) (a*200+b);
Run Code Online (Sandbox Code Playgroud)
然后参考我的blob:
memory[INDX(a,b)];
Run Code Online (Sandbox Code Playgroud)
我更喜欢:
memory[a][b];
Run Code Online (Sandbox Code Playgroud)
int *MAGICVAR[][200] = memory;
Run Code Online (Sandbox Code Playgroud)
没有这样的语法吗?请注意我不仅使用固定宽度数组的原因是它太大而无法放在堆栈上.
void toldyou(char MAGICVAR[][286][5]) {
//use MAGICVAR
}
//from another function:
char *memory = (char *)malloc(sizeof(char)*1820*286*5);
fool(memory);
Run Code Online (Sandbox Code Playgroud)
我收到警告,passing arg 1 of toldyou from incompatible pointer type但代码有效,我已经确认访问了相同的位置.没有使用其他功能有没有办法做到这一点?
caf*_*caf 27
是的,你可以做到这一点,不,你不需要像大多数其他答案告诉你的另一个指针数组.你想要的调用只是:
int (*MAGICVAR)[200] = malloc(400 * sizeof *MAGICVAR);
MAGICVAR[20][10] = 3; // sets the (200*20 + 10)th element
Run Code Online (Sandbox Code Playgroud)
如果你想声明一个返回这样一个指针的函数,你可以这样做:
int (*func(void))[200]
{
int (*MAGICVAR)[200] = malloc(400 * sizeof *MAGICVAR);
MAGICVAR[20][10] = 3;
return MAGICVAR;
}
Run Code Online (Sandbox Code Playgroud)
或者使用typedef,这使它更清晰:
typedef int (*arrayptr)[200];
arrayptr function(void)
{
/* ... */
Run Code Online (Sandbox Code Playgroud)
Tim*_*fer 19
使用指向数组的指针:
#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;
}
Run Code Online (Sandbox Code Playgroud)
如果不需要额外的间接寻址,您可以使用指针数组。
编辑
这是 @Platinum Azure 答案的一个变体,它不会对 malloc 进行如此多的调用。除了更快的分配之外,所有元素都保证是连续的:
#define ROWS 400
#define COLS 200
int **memory = malloc(ROWS * sizeof(*memory));
int *arr = malloc(ROWS * COLS * sizeof(int));
int i;
for (i = 0; i < ROWS; ++i)
{
memory[i] = &arr[i * COLS];
}
memory[20][10] = 3;
Run Code Online (Sandbox Code Playgroud)