gpt4 book ai didi

C:指向结构体内部函数的指针会导致段错误

转载 作者:行者123 更新时间:2023-11-30 19:34:16 27 4
gpt4 key购买 nike

我必须创建链接列表。在这些列表中,我将定义指向函数的指针。我的错误是每当我调用该函数时,我都会收到段错误错误。任何人都可以帮忙吗,下面是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


typedef struct CommandStructure{
char CommandName[10];
char ShortKey;
void (* CommandAction)(void);
} CommandFrame;

typedef struct LinkedCommandsStructure{
CommandFrame * Entity;
struct LinkedCommandsStructure * NextCommand;
} Firmware_Command;


void PrintSEQHelp(){
printf("HelloPrint \n");
}


CommandFrame * SEQ_Help(){
CommandFrame * Entity = malloc(sizeof(Entity));

strcpy(Entity->CommandName, "help");

Entity->ShortKey = 'h';

Entity->CommandAction = PrintSEQHelp;

return Entity;
}



Firmware_Command * SEQ_CommandsInit(){

Firmware_Command * HeadOfCommands = malloc(sizeof(HeadOfCommands));
Firmware_Command * HelpCommand = malloc(sizeof(HelpCommand));

HelpCommand->Entity = SEQ_Help();

HelpCommand->NextCommand = NULL;

HeadOfCommands = HelpCommand;

return HeadOfCommands;
}


void callcommand(Firmware_Command * ActiveCommands){
ActiveCommands = malloc(sizeof * ActiveCommands);
printf("inside callcommand \n");

(ActiveCommands->Entity->CommandAction)();

}


int ModulesInit() {

int ParseRet;

Firmware_Command * ActiveCommands = malloc(sizeof(ActiveCommands));

ActiveCommands = SEQ_CommandsInit();
callcommand(ActiveCommands);

return 1;
}



void main(void){
int cmdInitRet;

cmdInitRet = ModulesInit();
}

最佳答案

您可以在有变量的代码中多次执行此操作,并为其分配内存,然后用其他值覆盖它。或者分配先前的值。至关重要的是,在 callcommand 函数中,您传入一个变量,然后用新的未初始化内存块覆盖它的值,然后尝试使用它。您不需要分配内存 - 传入的变量应该已经是有效的指针。

void callcommand(Firmware_Command * ActiveCommands){
// ActiveCommands = malloc(sizeof * ActiveCommands); Not needed at all
printf("inside callcommand \n");

(ActiveCommands->Entity->CommandAction)();

}

关于C:指向结构体内部函数的指针会导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44117747/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com