我编写了下面的代码来为嵌套结构动态分配内存: Product **product;
我的代码的目的是让我学习动态分配内存以供使用的正确或更好的方法指向结构体的双指针位于另一个指向结构体的指针中。代码运行良好。
问题:代码有任何更正或改进吗?预先感谢您分享您的经验。
typedef struct {
int price;
} Product;
typedef struct {
Product **product;
int id;
} Inventory;
int main() {
int i, j, k, count=0;
int n1=2, n2=3, n3=2;
Inventory *inventory = malloc(n1 * sizeof *inventory);
for (i=0; i<n1; i++) {
inventory[i].product = malloc(n2 * sizeof *inventory[i].product);
for (j=0; j<n2; j++) {
inventory[i].product[j] = malloc(n3 * sizeof *inventory[i].product[j]);
}
}
for (i=0; i<n1; i++) {
for (j=0; j<n2; j++) {
for (k=0; k<n3; k++) {
inventory[i].product[j][k].price = count++;
printf("%d " , inventory[i].product[j][k].price);
}
}
}
return 0;
}
Output: 0 1 2 3 4 5 6 7 8 9 10 11
最佳答案
我尝试过使用更大的 n1
、n2
和 n3
,并且您的代码也可以正常工作。
但是这里有两点需要注意:
1.使用malloc()
分配内存后,需要添加free()
。
2. 如果要使用 C++ 编译器(例如 g++)编译此代码,则需要对 malloc()
函数返回的指针类型进行强制转换.
以下是我测试的代码。运行它会花费一些时间:
#include "stdlib.h"
#include "stdio.h"
typedef struct {
int price;
} Product;
typedef struct {
Product **product;
int id;
} Inventory;
int main() {
int i, j, k, count=0;
int n1=525, n2=33, n3=141;
Inventory *inventory = (Inventory*)malloc(n1 * sizeof *inventory);
for (i=0; i<n1; i++) {
inventory[i].product = (Product**)malloc(n2 * sizeof *inventory[i].product);
for (j=0; j<n2; j++) {
inventory[i].product[j] = (Product*)malloc(n3 * sizeof *inventory[i].product[j]);
for (k=0; k<n3; k++) {
inventory[i].product[j][k].price = k*i*j;
}
}
}
for (i=0; i<n1; i++) {
for (j=0; j<n2; j++) {
for (k=0; k<n3; k++) {
printf("%d\n", inventory[i].product[j][k].price);
}
}
}
for (i=0; i<n1; i++) {
for (j=0; j<n2; j++) {
free(inventory[i].product[j]);
}
free(inventory[i].product);
}
free(inventory);
return 0;
}
希望有帮助。
关于c - 改进了在结构指针内为结构双指针动态分配内存的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29873777/