[英]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.