首页 > 解决方案 > 结构的 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();
}

上述代码的输出是:

我正在尝试 malloc 二维数组(stackOfPlates->stackOfPlatesArray)。在NEW_STACKS_CREATION_INC为堆栈数分配内存后,我MAX_PLATES_PER_STACK为每个堆栈分配内存。在此操作期间,我发现 mystackOfPlates->currentMaxStacks被修改为0.

有人可以解释为什么吗?

标签: cpointersstructmalloc

解决方案


在您的代码中

 malloc(sizeof(stackOfPlates));

应该

malloc(sizeof(*stackOfPlates));

因为您想为结构类型而不是指向结构类型的指针分配内存。

也就是说,看到这个:我会转换 malloc 的结果吗?


推荐阅读