c - 结构的 int 字段在同一结构的 int* 上的 malloc() 之后被修改
问题描述
#define MAX_NUM_STACKS_ALLOWED 10
#define MAX_PLATES_PER_STACK 5
#define NEW_STACKS_CREATION_INC 2
typedef struct stackOfPlates {
int currentStackIndex;
int currentStackTop[MAX_NUM_STACKS_ALLOWED];
int currentMaxStacks;
int **stackOfPlatesArray;
} stackOfPlates_t;
stackOfPlates_t *stackOfPlates_Init(void) {
stackOfPlates_t *stackOfPlates = (stackOfPlates_t *)malloc(sizeof(stackOfPlates));
stackOfPlates->stackOfPlatesArray = (int **)malloc(NEW_STACKS_CREATION_INC * sizeof(int *));
stackOfPlates->currentStackIndex = 0;
stackOfPlates->currentMaxStacks = NEW_STACKS_CREATION_INC;
int i;
for (i = 0; i < stackOfPlates->currentMaxStacks; i++) {
stackOfPlates->stackOfPlatesArray[i] = (int *)malloc(MAX_PLATES_PER_STACK * sizeof(int));
printf("%d\n", stackOfPlates->currentMaxStacks);
}
for (i = 0; i < MAX_NUM_STACKS_ALLOWED; i++) {
stackOfPlates->currentStackTop[i] = -1;
}
return stackOfPlates;
}
void main()
{
stackOfPlates_t *stackOfPlatesA;
stackOfPlatesA = stackOfPlates_Init();
}
上述代码的输出是:
- 2(预期),
- 0(未预期,不确定如何修改此字段)
我正在尝试 malloc 二维数组(stackOfPlates->stackOfPlatesArray
)。在NEW_STACKS_CREATION_INC
为堆栈数分配内存后,我MAX_PLATES_PER_STACK
为每个堆栈分配内存。在此操作期间,我发现 mystackOfPlates->currentMaxStacks
被修改为0
.
有人可以解释为什么吗?
解决方案
在您的代码中
malloc(sizeof(stackOfPlates));
应该
malloc(sizeof(*stackOfPlates));
因为您想为结构类型而不是指向结构类型的指针分配内存。
也就是说,看到这个:我会转换 malloc 的结果吗?
推荐阅读
- html - 为什么是s 在垂直居中时也垂直居中?(<input> 的 line-height 不等于它的 parent 高度)
- python - 面向对象的套接字 Python 客户端服务器。将修改后的客户端消息传递给服务器
- excel - 刷新 Pivot 需要开源工作簿
- r - 在 R 包内的 NAMESPACE 中导入 Rcpp 头文件
- angular - 响应式表单中表单控件的动态验证 - Angular 7
- reactjs - 此 CodeSandbox 中 jssPreset 的文档在哪里?我没找到
- html - 如何在 Outlook 上显示边框半径
- regex - 需要一个正则表达式,它接受 4 个数字和 1 个字符的格式完全相同
- nearprotocol - 什么是安全的 NEAR 区块链验证节点重启程序?
- arduino - Angle range of Gy-25 sensor