微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

指针失去价值?

如何解决指针失去价值?

我正在努力从函数返回结构。在我的情况下,它是makeValidInstructions函数。我成功地获得了第一个打印的值,但是第二个失败了。我不知道如何将结构放入数组。

typedef struct instruction {
    // enum
    commandName_t id;
    char** arguments;
    bool initializedProperly;
} instruction_t;

// Check if there is enough words for the number of command arguments and if so,validate the command
instruction_t validInstructions[MAX_NUMBER_OF_COMMANDS];
if (i + supportedCommands[j].argc < argc)
{
    instruction_t tempInstruction = makeValidInstructions(supportedCommands[j],argv,i,delimiter,tempInstruction);
    if (tempInstruction.initializedProperly)
    {
        if (validInstructionIndex < MAX_NUMBER_OF_COMMANDS)
        {
            validInstructions[validInstructionIndex] = tempInstruction;
            strcpy(*validInstructions[validInstructionIndex].arguments,*tempInstruction.arguments);
            // OK HERE
            printf("ADDED %i %s",validInstructionIndex,validInstructions[validInstructionIndex].arguments[0]);
            validInstructionIndex++;
        }
        else
        {
            fprintf(stderr,"ERROR - Max limit of commands exceeded! There can be no more than %i commands at a time",MAX_NUMBER_OF_COMMANDS);
        }
        // STOPS WORKING HERE
        printf("ADDED %i %s",validInstructions[validInstructionIndex].arguments[0]);
    }
}
else
{
    fprintf(stderr,"ERROR - Missing arguments for last command");
}

解决方法

            validInstructionIndex++;

在第一个printf之后执行,并且此语句在validInstructionIndex上加1,因此您必须减去1才能取消此更改。

        // STOPS WORKING HERE
        printf("ADDED %i %s",validInstructionIndex - 1,validInstructions[validInstructionIndex - 1].arguments[0]);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。