【问题标题】:Structure's int field gets modified after malloc() on the same structure's int*结构的 int 字段在同一结构的 int* 上的 malloc() 之后被修改
【发布时间】:2021-04-11 21:05:37
【问题描述】:
#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-&gt;stackOfPlatesArray)。在为NEW_STACKS_CREATION_INC 数量的堆栈分配内存后,我为每个堆栈分配MAX_PLATES_PER_STACK 的内存。在此操作过程中,我发现我的stackOfPlates-&gt;currentMaxStacks 被修改为0

谁能解释一下原因?

【问题讨论】:

    标签: c pointers struct malloc


    【解决方案1】:

    在您的代码中

     malloc(sizeof(stackOfPlates));
    

    应该是

    malloc(sizeof(*stackOfPlates));
    

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

    也就是说,看这个:Do I cast the result of malloc?

    【讨论】:

    • 谢谢苏拉夫!你说得对,我是想用malloc(sizeof(stackOfPlates_t)
    猜你喜欢
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 2016-04-10
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    相关资源
    最近更新 更多