[英]C99 - Why can't I use a variable-length char array in Xcode 6?
在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 :-)
编辑:好的,我似乎感到困惑,甚至可能在这里给几个人定罪(因为我在这个问题上至少获得3票赞成票),所以让我澄清一下。
我实际上是在Mac OS X Yosemite上编写一个libcurl应用程序,以通过HTTP将文件上传到Web服务器。 最后,我希望能够在终端中输入“ upload [目标url] [文件或目录1] [文件或目录2] ... [文件或目录N]”,然后让我的程序自动上传文件和目录到[目标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中文件路径的最大长度是多少? 等等,所以我更希望将其尺寸正确设置。
如果您勇敢地发表这篇文章的篇幅太长了,请到这里,谢谢您的耐心等待! 我最初试图尽可能简洁地描述问题,但这显然引起了混乱,因此我对此表示歉意:-)
int N;
scanf("%d",&N);
char a[N];
a
是VLA。 您的示例中显示的阵列不是VLA。
C99支持VLA。 如果您看不到输出,请尝试
printf("%s\n", test);
除此之外,您的代码看起来不错。
我最终对OS X中的最大路径长度进行了一些研究,并遇到了这个stackoverflow.com帖子 ,这使我<sys/syslimits.h>
使用<sys/syslimits.h>
的PATH_MAX
定义的想法。 这是可以接受的解决方案,因为该定义将始终在必要时进行更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.