【问题标题】:Triple stars: What's the difference between char* (*arr)[] and char*** arr (in C)?三颗星:char* (*arr)[] 和 char*** arr(在 C 中)有什么区别?
【发布时间】:2012-04-28 08:11:11
【问题描述】:

基本上,我有一个 char* 数组,我想在这个函数中传递和修改,所以我传入一个指向 char* 数组的指针。也就是说,我想传递一个指向 char* arr[] 的指针。两者有什么区别?

【问题讨论】:

    标签: c arrays pointers syntax


    【解决方案1】:

    一如既往,http://cdecl.org 是你的朋友:

    • char * (*arr)[] - “将 arr 声明为指向 char 指针数组的指针”
    • char *** arr - “将 arr 声明为指向 char 指针的指针”

    这些不一样。首先,第一个是不完整类型(为了使用指向数组的指针,编译器需要知道数组大小)。

    你的目标并不完全清楚。我猜你真正想做的就是修改char * 数组中的基础数据。如果是这样,那么您只需将指针传递给第一个元素:

    void my_func(char **pointers) { 
        pointers[3] = NULL;  // Modify an element in the array
    }
    
    char *array_of_pointers[10];
    
    // The following two lines are equivalent
    my_func(&array_of_pointers[0]);
    my_func(array_of_pointers);
    

    如果你真的想要传递一个指向数组的指针,那么这样的事情会起作用:

    void my_func(char *(*ptr)[10]) {
        (*ptr)[3] = NULL;  // Modify an element in the array
    }
    
    char *array_of_pointers[10];
    
    // Note how this is different to either of the calls in the first example
    my_func(&array_of_pointers);
    

    有关数组和指针之间重要区别的更多信息,请参阅 C 常见问题解答的专用章节:http://c-faq.com/aryptr/index.html。

    【讨论】:

    • 感谢您的资源和解释!这回答了我一直在寻找的东西。
    【解决方案2】:

    如果你有一个以char *(*arr)[]为参数的函数,你需要传入一个带有地址操作符的数组:

    void afunc(char *(*arr)[]);
    
    char *charptra, *charptrb, *charptrc;
    char *arr[] = {charptra, charptrb, charptrc};
    
    afunc(&arr);
    

    另一方面,你必须传递一个指向指针的指针:

    void afunc(char ***);
    
    char arr[] = "str";
    char *arrptr = arr;
    char **arrptrptr = &arrptr;
    char ***arrptrptrptr = &arrptrptr;
    
    afunc(arrptrptrptr);
    

    【讨论】:

    • 真的不行。当您尝试在函数内使用 arr 执行任何有用的操作时,您应该会立即收到编译器错误消息。
    • 我把(*ptr)[0] = NULL; 放在afunc(char *(*)[]) 里面。它编译。 0 个警告。 0 个错误。
    • 有趣。在 GCC 中使用等效的 ptr[0][0] 会导致“无效使用未指定边界的数组”错误消息。
    • 仅供参考,我创建了一个关于此主题的问题:stackoverflow.com/questions/10183943/…。
    • 感谢您的回答!这就是我在我的神秘描述中真正想要做的。
    猜你喜欢
    • 1970-01-01
    • 2013-05-16
    • 1970-01-01
    • 2021-09-16
    • 2011-07-26
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    • 2014-03-21
    相关资源
    最近更新 更多