C释放动态分配的结构数组

问题描述 投票:0回答:1

对不起,如果已经对此进行了讨论,但是我似乎找不到与我遇到的问题有关的任何东西。在下面的代码中,我试图创建一个结构数组,这些结构将传递给许多不同的函数。我需要动态分配数组,因为它会根据用户输入的指令数量而变化。我不确定我使用malloc()的变量声明是否不正确,但是在每次运行时,我在free(指令)行上都会遇到断点。我也尝试过将free(指令)行放在if语句之外,但它会产生相同的结果。这是一项家庭作业,任何提示或解释将不胜感激。

struct instructions
{
char destination_register[3] , reg1[3], reg2[3];//declaration of destination and source registers.
int delay;

};struct instructions* instruction;

 int main(){

int input=0;
char test1[2];
int test,numberofinstructions=0;

do{

    printf("Pipelined instruction performance\n1) Enter instructions\n2) Determine when instructions are fetched\n3) Exit\nEnter selection : ");
    scanf("%d",&input);
    if (input==1) {
        printf("Enter number of instructions: ");
        scanf("%d", &numberofinstructions);

        instruction = (struct instructions*) malloc(numberofinstructions + 1 * sizeof(struct instructions));
        enterinstructs(instruction,numberofinstructions);

        printf("\n");
        free(instruction);
    }
} while (input != 3);



    return 1;

}

c pointers malloc free dynamic-arrays
1个回答
0
投票

我认为您不需要这样做:

© www.soinside.com 2019 - 2024. All rights reserved.