gpt4 book ai didi

c - 在 C 中声明二维数组只知道一个的长度

转载 作者:太空宇宙 更新时间:2023-11-04 04:10:48 26 4
gpt4 key购买 nike

我在 C 中工作,我试图在只知道一个长度的情况下声明一个二维数组(我最初只知道有多少“行”,不知道有多少“列”)。我知道在不知道初始大小的情况下声明一个普通数组

int *rows = null;

稍后调用

rows = malloc(sizeof(int)*10);

会工作,但是我可以为二维数组做类似的事情吗?

最佳答案

看我的例子给你 2 个想法分配二维数组

#include <stdio.h>
#include <stdlib.h>


int main(){
//Example Ar_2D[20][50] from alloc
//method 1
int i;
int **Ar_2D=(int**)malloc(sizeof(int*)*20);

for(i=0;i<20;i++){
Ar_2D[i]=(int*)malloc(sizeof(int)*50);
}
//----------------------do everything you want with Ar_2D[20][50]
//using this method cause below
//&(Ar_2D[0][49])+1 != &(Ar_2D[1][0]) means not always == if you are luck will ==
if(&(Ar_2D[0][49])+1 != &(Ar_2D[1][0])){
printf("you are right about Ar_2D!\n");
}


//----------------------Release memory alloc
for(i=0;i<20;i++){
free(Ar_2D[i]);
}
free(Ar_2D);

//----------------------

//Example Ar_2D_M2[20][50] from alloc
//method 2
int **Ar_2D_M2=(int**)malloc(sizeof(int*)*20);
int *Ar_1D=(int*)malloc(sizeof(int)*50*20);
for(i=0;i<20;i++){
Ar_2D_M2[i]=&(Ar_1D[i*50]);
}
//----------------------do everything you want with Ar_2D_M2[20][50]
//using this method cause below
//&(Ar_2D_M2[0][49])+1 == &(Ar_2D_M2[1][0]) always ==
if(&(Ar_2D_M2[0][49])+1 == &(Ar_2D_M2[1][0])){
printf("you are right about Ar_2D_M2!\n");
}

//----------------------Release memory alloc
free(Ar_1D);
free(Ar_2D_M2);
return 0;
}

方法2会给你

1 2 3... 20

21 ...... 40

41 ...... 60

...

二维数组中的良好顺序(ponter)

3D 4D 5D 就像这个从 1D 构建

关于c - 在 C 中声明二维数组只知道一个的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57862497/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com