c/c++语言开发共享在C中,当作为参数传递给函数时,修改指向指针数组的指针的目标

我想要一个返回给定目录内容的函数。 为此,我使用dirent.h scandir 。 下面的代码成功编译(gcc -Wall test.c),但最后一个printf导致分段错误。 这意味着“eps”结构(指向指向结构的指针数组的指针)在函数后仍然是空的:我该如何解决这个问题?

 #include  #include  #include  #include  static int myselector(const struct dirent * dir_entry) { char * pch = strstr(dir_entry->d_name, "."); return pch == NULL ? 1 : 0; } int list_dir(char * dirname, struct dirent ** eps) { int nbfiles = scandir(dirname, &eps, myselector, alphasort); if(nbfiles > 0) { printf("inside function: %sn", eps[0]->d_name); return 1; } else return 0; } int main(int argc, char *argv[]) { int status = 0; struct dirent ** eps = NULL; status = list_dir("/home", eps); if (status) { puts("ok"); printf("outside function: %sn", eps[0]->d_name); } return EXIT_SUCCESS; } 

    因为你的指针已经改变了,你在main() :)中看错了

    您正在传递指向指向scandir()的指针的指针。 它正在改变指向指针的指针(我知道,这会伤害阅读……)。

    因为您在函数中使用&eps调用scandir() ,所以在函数之外会丢失该更改。 eps的值在您的函数内发生了变化。

    为了更好地理解这一点,在当前函数中使用printf()语句包装scandir()调用,显示eps包含的值是什么:

     ... printf("%pn", eps); int nbfiles = scandir(dirname, &eps, myselector, alphasort); printf("%pn", eps); ... 

    要解决此问题,请将您的function更改为

     int list_dir(char * dirname, struct dirent *** eps) { int nbfiles = scandir(dirname, eps, myselector, alphasort); if(nbfiles != -1) { printf("inside function: %sn", (*eps)[0]->d_name); return 1; } else return 0; } 

    并称之为……

     status = list_dir("/home", &eps); 

    main() 。 它将完美地工作:

    broach @ roach-VirtualBox:〜$ ./test
    内function:拉刀

    外部function:拉刀

    你似乎没有覆盖scandir返回0的情况,即空目录。 返回值-1仅用于错误。

    使list_dir取struct dirent ***而不是struct dirent ** ,去除scandir()调用中的&运算符,并将其添加到main的list_dir()调用中。 list_dir()的第一行成为:

     int list_dir(char * dirname, struct dirent *** eps) { int nbfiles = scandir(dirname, eps, myselector, alphasort); 

    并且main中的list_dir()调用变为:

     status = list_dir("/home", &eps); 

    这样,list_dir()可以让scandir()通过其地址修改main()中的eps ,而不是修改堆栈上的参数,传递给list_dir()。

      以上就是c/c++开发分享在C中,当作为参数传递给函数时,修改指向指针数组的指针的目标相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/549788.html

      (0)
      上一篇 2021年1月14日
      下一篇 2021年1月14日

      精彩推荐