Search code examples
cpointersstructreturn

Pointer loosing value?


I am struggling returning struct from a function. In my case it is the makeValidInstructions function. I successfuly get the value on the first print, but the second one fails. I have no idea how to get the struct into the array.

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");
}

Solution

  •             validInstructionIndex++;
    

    is executed after the first printf and this statement adds 1 to validInstructionIndex, so you have to subtract 1 to cancel this change.

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