这应该很容易回答,但我更难在Google或K&R上找到特定的正确答案.我也完全可以忽视这一点,如果是这样,请让我直截了当!
相关代码如下:
int main(){
char tokens[100][100];
char *str = "This is my string";
tokenize(str, tokens);
for(int i = 0; i < 100; i++){
printf("%s is a token\n", tokens[i]);
}
}
void tokenize(char *str, char tokens[][]){
int i,j; //and other such declarations
//do stuff with string and tokens, putting
//chars into the token array like so:
tokens[i][j] = <A CHAR>
}
Run Code Online (Sandbox Code Playgroud)
所以我意识到我不能char tokens[][]在我的tokenize函数中,但如果我输入char **tokens,我会收到编译器警告.此外,当我尝试将char添加到我的char数组中时tokens[i][j] = <A CHAR>,我发生了段错误.
我哪里错了?(以及有多少种方式......我该如何解决?)
非常感谢!
您需要指定数组的第二个维度的大小:
#define SIZE 100
void tokenize(char *str, char tokens[][SIZE]);
Run Code Online (Sandbox Code Playgroud)
这样,编译器知道当你说它tokens[2][5]需要执行以下操作时:
tokensSIZE在开始之后移动2*个字节如果没有指定第二个维度,如果你说它tokens[2][5]怎么会知道去哪里?