简体   繁体   English

对三重指针的作用极为困惑

[英]Extremely confused about the role of triple pointers

int main()
{
    char** subject_array;
    char** courses_array;    

    initialize(subject_array, courses_array);
}


void initialize(char*** subject_array, char*** courses_array)
{
    int i;

    *subject_array = (char**) malloc(100 * sizeof(char*)); // 100 char pointers
    *courses_array = (char**) malloc(100 * sizeof(char*));

    for(i = 0; i < 100; i++) //malloc for subject_array
    {
        (*subject_array)[i] = (char*) malloc(4 * sizeof(char)); // 4 chars for each
        (*courses_array)[i] = (char*) malloc(6 * sizeof(char)); // char pointer
    }

} //void initialize

My question is: Why is there a discrepancy between the declared double pointers in main and the triple pointers in the initialize function? 我的问题是:为什么在main中声明的双指针与initialize函数中的三指针之间存在差异? I think the triple pointer allows me to modify where the 2d array points. 我认为三重指针允许我修改2d数组指向的位置。

My assignment gives these requirements: 我的作业提出了以下要求:

Since you will be changing to where the pointers point, this will involve triple pointers for subjects and courses! 由于您将更改为指针指向的位置,因此涉及主题和课程的三重指针!

The above code takes care of bolded requirement but I have absolutely no idea what this even means. 上面的代码照顾了粗体的要求,但是我完全不知道这甚至意味着什么。 Can someone break it down to me? 有人可以把它分解给我吗? Does that mean I can modify contents of the 2d arrays of subject_array and courses_array? 这是否意味着我可以修改subject_array和courses_array的二维数组的内容? Such as swapping? 如交换? But I can do that already with just double pointers making a 2d array! 但是我已经可以使用双指针制作2d数组了! WHY triple pointers? 为什么三重指针?

First of all, the code is incorret, because initialize asks for char*** 's and main gives it char** 's. 首先,代码是不正确的,因为initialize要求使用char*** ,而main则要求使用char** To add another "pointer level", you take the address of whatever you want to give it to. 要添加另一个“指针级别”,请使用您想要赋予它的地址。 So, the last line of main shall read initialize(&subject_array, &courses_array) (or shall it be return 0 ?) 因此, main的最后一行应读取initialize(&subject_array, &courses_array) (或者应return 0 )。

After all, if you don't need to modify the variable subject_array and courses_array themselves, not what they point to , you may remove those pointers. 毕竟,如果您不需要自己修改变量subject_arraycourses_array ,而不是它们指向的内容 ,则可以删除这些指针。 And you actually do modify those variables themselves by means of *var = malloc(...) . 实际上,您确实可以通过*var = malloc(...) 修改这些变量 And, as I already noted, the only problem is that the arguments to initialize are char***, char*** , not char**, char** as main is doing. 而且,正如我已经指出的,唯一的问题是, initialize 要使用的参数 char***, char***而不是 char**, char**因为main正在这样做。

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

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