【问题标题】:Pointer loosing value?指针失去价值?
【发布时间】:2021-02-21 08:10:18
【问题描述】:

我正在努力从函数返回结构。就我而言,它是 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", validInstructionIndex, validInstructions[validInstructionIndex].arguments[0]);
    }
}
else
{
    fprintf(stderr, "ERROR - Missing arguments for last command");
}

【问题讨论】:

  • 欢迎来到 SO。不幸的是,我在这里没有看到makeValidInstructions() 函数,只是从一些没有被函数包围的代码中调用一个函数。确保在询问“为什么我的代码不起作用”问题时发布 minimal reproducible example,以确保您所面临的问题实际上可以通过您发布的代码重现
  • 你也将面临下一个错误:validInstructions 在堆栈上,因此从声明它的函数返回后它将不再有效。

标签: c pointers struct return


【解决方案1】:
            validInstructionIndex++;

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多