0

In my main function, I declare a variable length array of c strings and then pass it into a function called secondPass()

In secondPass(), I run a loop that determines the contents of a string called dec_instruction, then I try to add it to my array.

int main(int argc, char *argv[]) {

    /* Logic to decide num_commands */

    char machine_instructions[num_commands][11];
    secondPass(machine_instructions, num_commands);
}


secondPass(char **machine_instructions, int num_commands){
    for(int i = 0; i < num_commands; ++i){
        char dec_instruction[11];

        /* Logic to decide contents of dec_instruction */

        strcat(machine_instructions[i], dec_instruction);
    }
}

Sorry I can't post the complete contents of my code. This is for a class project and the rules on sharing code are pretty strict.

Anyway, the strcat() line near the end throws EXC_BAD_ACCESS when on the second iteration, when i = 1. As far as I can tell, dec_instruction is a valid c string like any other. What's causing my error?

3
  • 1
    char ** cannot point to char [][]. machine_instructions[1] will be sizeof(char*) past machine_instructions[0] Commented Sep 14, 2017 at 19:44
  • You should have gotten a type error from your compiler for either the call or the function declaration. Commented Sep 14, 2017 at 19:46
  • char dec_instruction[11]; ... strcat(machine_instructions[i], dec_instruction); is a problem as code attempts to concatenate a string to an array that is not certainly a string. Ask yourself, what are the contents of dec_instruction[] before the strcat() call? Commented Sep 14, 2017 at 20:01

1 Answer 1

1

Argument char **machine_instructions does not denote a 2D-Array of type char[][11] but a pointer to a pointer to a char. This is often used as a pointer to an "array" of pointers, but it is never an array of arrays of chars.

So in your code, machine_instructions[i] will try to dereference a pointer to char, but the content you pass consists of plain characters and not of pointer values. Therefore the BAD_EXCESS.

Using char machine_instructions[][11] should solve the problem.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.