指向指针的指针不存储所有值 - 仅存储最后一个值

时间:2017-01-14 03:19:24

标签: c

问题是当我尝试打印的值时 (*names)[*number],我只收到存储的最后一个。

我将用一个例子来解释我的意思 - 我想要的是:

 (*names)[0] = "john"
 (*names)[1] = "bill"
 (*names)[2] = "nick"

当我打印(*names)[*number]的值时,我得到的是:

 (*names)[0] = "nick"
 (*names)[1] = "nick"
 (*names)[2] = "nick"

以下是代码:

int GetFiles(char **dir,char ***names,int *number)
{
    struct dirent *dp;
    DIR *fd;
    int i;

    if ((fd = opendir(*dir)) == NULL)
    {
        printf("Can't open directory %s!\n",*dir);
        return 0;
    }
    *number = 0;

    //*names = (char**)malloc(((*number)+1) * sizeof(char*));

    *names = (char**)malloc(17*sizeof(char*));

    while ((dp = readdir(fd)) != NULL)
    {
        if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
        {
            continue;
        }

        (*names)[*number] = dp->d_name;

        (*number)++;

        //*names = (char**)realloc(*names,((*number)+1) * sizeof(char*));
    }

    closedir(fd);

    for(i=0;i<*number;i++)
    {
        printf("--%s\n",(*names)[i]);
    }

    system("PAUSE");
    return 1;
}

0 个答案:

没有答案