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

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

问题描述:

在我的主要功能,我声明C字符串的可变长度数组,然后将其传递到称为secondPass()函数传递C字符串中的可变长度数组作为函数参数

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

对不起,我无法发布我的代码的完整内容。这是一个课程项目,关于共享代码的规则非常严格。

无论如何,在第二次迭代时,当i = 1时,接近末尾的strcat()行会抛出EXC_BAD_ACCESS。据我所知,dec_instruction是一个有效的c字符串,与其他字符串一样。什么导致我的错误?

+1

char **不能指向char [] []'。 'machine_instructions [1]''sizeof(char *)''过去'machine_instructions [0]' –

+0

你应该从你的编译器得到一个类型错误的调用或函数声明。 – melpomene

+0

'char dec_instruction [11]; ... strcat(machine_instructions [i],dec_instruction);'是一个问题,因为代码尝试将字符串连接到不是_string_的数组。问问你自己,'strcat()'调用之前'dec_instruction []'的内容是什么? – chux

参数char **machine_instructions不表示char[][11]类型的2D阵列,而是指向指向字符的指针的指针。这通常用作指向指针“数组”的指针,但它绝不是一个由chars数组组成的数组。

因此,在您的代码中,​​会尝试将指针取消引用到char,但传递的内容由纯字符而非指针值组成。因此BAD_EXCESS

使用char machine_instructions[][11]应该解决问题。