代码之家  ›  专栏  ›  技术社区  ›  Isaac

声明字符指针数组(arg传递)

c
  •  4
  • Isaac  · 技术社区  · 16 年前

    这是一个很容易回答的问题,但对于我来说,在谷歌或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>
    }
    

    所以我意识到我不能 char tokens[][] 在我的标记化函数中,但是如果我 char **tokens 相反,我得到一个编译器警告。此外,当我尝试将char放入char数组时, tokens[i][j] = <A CHAR> 我错了。

    我哪里出错了?(在很多方面……我该怎么修复它呢?)

    非常感谢!

    2 回复  |  直到 16 年前
        1
  •  5
  •   Mark Rushakoff    16 年前

    您需要指定数组的第二个维度的大小:

    #define SIZE 100
    void tokenize(char *str, char tokens[][SIZE]);
    

    这样,当你说 tokens[2][5] 它需要做如下的事情:

    1. 查找的地址 tokens
    2. 移动2 SIZE 超过起始字节数
    3. 再移5个字节 那个 地址
    4. ????
    5. 利润!

    如果你说 令牌〔2〕〔5〕 它怎么知道去哪里?

        2
  •  3
  •   Carl Norum    16 年前

    你离我很近。数组和指针不是一回事,尽管有时看起来它们是一样的。您可以使用指针生成二维数组:

     char **tokens = malloc(100 * sizeof(char *));
     for (i = 0; i < 100; i++)
         tokens[i] = malloc(100);
    

    然后使用:

    void tokenize(char *str, char **tokens)
    

    或者您可以在 tokenize() 功能:

    void tokenize(char *str, char tokens[][100])