简体   繁体   English

将C字符串的可变长度数组作为函数参数传递

[英]Passing variable length array of c strings as function argument

In my main function, I declare a variable length array of c strings and then pass it into a function called secondPass() 在我的主函数中,我声明了一个可变长度的c字符串数组,然后将其传递给名为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. 在secondPass()中,我运行一个循环,该循环确定名为dec_instruction的字符串的内容,然后尝试将其添加到数组中。

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. 无论如何,在第二次迭代中,当i = 1时,靠近末端的strcat()行会抛出EXC_BAD_ACCESS。据我所知,dec_instruction是一个有效的c字符串,与其他字符串一样。 What's causing my error? 是什么导致我的错误?

Argument char **machine_instructions does not denote a 2D-Array of type char[][11] but a pointer to a pointer to a char. 参数char **machine_instructions并不表示char[][11]类型的2D数组,而是指向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. 因此,在您的代码中, machine_instructions[i]将尝试取消对char的指针的引用,但是您传递的内容由普通字符而不是指针值组成。 Therefore the BAD_EXCESS . 因此, BAD_EXCESS

Using char machine_instructions[][11] should solve the problem. 使用char machine_instructions[][11]应该可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM