gpt4 book ai didi

c - 我如何在c中使用动态二维数组

转载 作者:太空狗 更新时间:2023-10-29 15:13:49 26 4
gpt4 key购买 nike

我试图制作一个动态的 5x5 int 数组

int **data=malloc(5*5);

但是我在尝试访问它时遇到段错误。

最佳答案

你需要为你想要制作的二维数组分配内存(我想你明白了)。但首先,您必须为指针分配空间,您将在其中存储二维数组的行。

int **data=(int**)malloc(sizeof(*data)*5); //Here 5 is the number of rows

现在您可以为每一行分配空间。

for(int r=0;r<5;r++){
data[r]=(int*)malloc(sizeof(**data)*5);//here 5 is the width of the array
}

如果您想要整个数组的连续内存块,您可以分配一个大小为 25 的单维数组,并像 data[r*5+c] 一样访问它。

PS: 除了 sizeof(*data)sizeof(**data),您还可以使用 sizeof(int*)sizeof(int) 以避免与 *

混淆

PS:如果您不使用 C++,从 malloc 的返回值中删除强制转换会更好(参见评论)。

关于c - 我如何在c中使用动态二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33811484/

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