指针失去价值?

问题描述

我正在努力从函数返回结构。在我的情况下,它是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]);