-1

在 Xcode 6 中获得了一个 C 命令行工具项目,除了一件小事之外,一切都很好:我一生都无法弄清楚如何为可变长度数组赋值!例如,考虑以下代码:

#include <string.h>
int main()
{
    int len = 10;
    char str[len];
    strcpy(str, "hello");
    printf("%s", str);
}

这编译得很好,但是当我调试它时,数组永远不会被分配!如果我在第 7 行设置断点,点击运行按钮并将鼠标悬停在 上str,它只会显示该名称,旁边有一个箭头,展开后什么也不显示!

如果我错了,请纠正我,但我相信这是我在这里写的完全有效的 C99 代码……那是什么?!我已经尝试过 GNU99 编译器(默认)和 C99 编译器,但均无济于事。

MTIA :-)

编辑:好的,我似乎对这里的一些人感到困惑,甚至可能是 PO'ed (因为我在这个问题上至少获得了 3 票反对票)所以让我稍微澄清一下。

我实际上是在 Mac OS X Yosemite 上编写一个 libcurl 应用程序,以通过 HTTP 将文件上传到 Web 服务器。最后,我希望能够在终端中输入“上传 [目标 URL] [文件或目录 1] [文件或目录 2] ... [文件或目录 N]”之类的内容,并让我的程序自动上传这些内容文件和目录到 [destination url]。输入的路径可以是相对于 CWD 或绝对的。

问题存在于我的uploadDirectory函数中,如下所示:

void uploadDirectory(CURL* hnd, struct curl_httppost* post,
    struct curl_httppost* postEnd, char* path, const char* url)
{
    DIR* dir = opendir(path);
    if (dir == NULL)
    {
        printf("\nopendir failed on path \"%s\"", path);
        perror(NULL);
    }
    else
    {
        struct dirent* file;
        while ((file = readdir(dir)) != NULL)
        {
            // skip the current directory and parent directory files
            if (!strcmp(file->d_name, ".") ||
                !strcmp(file->d_name, ".."))
                continue;

            if (file->d_type == DT_REG)
            {
                // file is an actual file; upload it
                // this is the offending code
                char filePath[strlen(path) + strlen(file->d_name) + 2];
                strcpy(filePath, path);
                strcat(filePath, "/");
                strcat(filePath, file->d_name);

                int res = uploadFile(hnd, post, postEnd, filePath, url);
                printf("%d", res);
            }
            if (file->d_type == DT_DIR)
            {
                // file is a directory; recurse over it
                // this section is omitted for brevity
            }
        }
        closedir(dir);
    }
}

我知道我可以定义filePath一个巨大的常量大小来解决问题,但是多大才算太大?OS X 中文件路径的最大长度是多少?等等,等等……所以我宁愿把它做​​成合适的尺寸。

如果你冒着这篇文章的极端篇幅来到这里,谢谢你的耐心!我最初试图尽可能简洁地描述这个问题,但这显然只会引起混乱,所以我为此道歉:-)

4

2 回答 2

1
int N;
scanf("%d",&N);

char a[N];

a是一个 VLA。您的示例中显示的数组不是 VLA。

C99 支持 VLA。如果您看不到输出,请尝试

printf("%s\n", test);

除此之外,您的代码看起来不错。

于 2015-01-22T17:10:39.973 回答
1

我最终对 OS X 中的最大路径长度进行了一些研究,并遇到了这个 stackoverflow.com 帖子,它给了我使用定义<sys/syslimits.h>的想法。PATH_MAX这是一个可接受的解决方案,因为该定义将始终在必要时更新。

于 2015-01-23T13:32:36.953 回答