在 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(因为我在这个问题上至少获得了 3 票否决票),所以让我澄清一下。
我实际上正在 Mac OS X Yosemite 上编写一个 libcurl 应用程序,用于通过 HTTP 将文件上传到 Web 服务器。最后,我希望能够在终端中输入类似“上传[目标网址] [文件或目录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);
}
}
我知道我可以定义一个巨大的常量大小来解决这个问题,但是多大才算太大呢? OS X 中文件路径的最大长度是多少?等等,等等...所以我更愿意使其尺寸完全正确。
如果您冒着这篇文章的冗长来到这里,感谢您的耐心!我最初试图尽可能简洁地描述这个问题,但这显然只会造成困惑,所以我为此道歉:-)
最佳答案
int N;
scanf("%d",&N);
char a[N];
a
是 VLA。您的示例中显示的数组不是 VLA。
C99 支持 VLA。如果您看不到输出,请尝试
printf("%s\n", test);
除此之外,您的代码看起来不错。
关于C99 - 为什么我不能在 Xcode 6 中使用变长字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28094580/