创建 argv[] 以将参数发送到另一个函数

标签 c function malloc argv

我知道有一些关于此的条目,我浏览了它们,但无法完全到达我想要的地方。

我正在构建函数,它可以读取目录的内容并将常规文件传递给另一个函数以构建存档。

我正在尝试创建一个类似于 argv[] 的项目,称为项目,我可以将其传递给我的函数,问题是我需要用文件名填充它。我想根据文件计数使用 malloc,而不是静态声明它(我在很多示例中看​​到)。

这是快速的函数头:

void quick(int argc, char *argv[])

这是附加函数:

void append(char* argv[]){
    struct dirent *dp;
    int count, i = 3;
    char *files;
    char items [*files][255];
    DIR *dirp = opendir(".");
    if(dirp == NULL){
        fail('f');
    }

    printf("ar: adding files in current directory to archive: %s", argv[2]);

    while((dp = readdir(dirp)) != NULL){
        if(dp->d_type == DT_REG){
            count++;
        }
    }

    rewinddir(dirp);
    files = malloc(count*sizeof(char));

    //copy argv[2] archive name, into files, so we can pass to quick
    strcpy(items[2], argv[2]);

    while((dp = readdir(dirp)) != NULL){
        errno = 0;
        dp = readdir(dirp);

        //leave is dir is empty
        if(dp == NULL)
            break;

        // Skip . and ..
        if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0)
            continue;

        //if file is not the archive and a regular file add to list
        if(strcmp(dp->d_name, argv[2]) != 0 && dp->d_type == DT_REG){
            strcpy(items[i], dp->d_name);
            i++;
        }
    }
    closedir(dirp);

    quick(i, items);
}

我在 items arg 上收到错误,因为指针类型不兼容,我猜测我没有正确执行 malloc(可能还有我的数组),因为我仍然没有掌握这些的奥秘。

最佳答案

您对char 项[*files][255] 的声明不正确。

基本上,您希望files 是一个数组的数组;因此它必须是指针到指针(即 char**)类型。然后,您需要分配该数组中的每个数组来保存实际的字符串,如下所示:

char** files;
files = malloc(count * sizeof(char*));      // allocate the array to hold the pointer
for (size_t i = 0; i < count; i += 1)
    files[i] = malloc(255 * sizeof(char));  // allocate each array to hold the strings

使用完毕后适当释放内存:

for (size_t i = 0; i < count; i += 1)
    free(files[i]);
free(files);

关于创建 argv[] 以将参数发送到另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14667396/

相关文章:

c - 在 C 中将数组声明为指针

c - 创建多个具有互斥锁和不同生命周期的线程

c - 删除链接排序列表中的第一个元素

algorithm - 这个伪代码的时间复杂度是多少?

javascript - 属性(property)值(value)已改变但不受影响

python - 使用 scipy 最小化二参数函数时的性能问题

c - 结构,malloc ..我再困惑不过了

c - Bison 规范和优先顺序

c - 如何在 C 中的给定地址动态分配内存?

c - 将字符串复制到 malloc 的 char 数组中失败并出现段错误