簡體   English   中英

為什么我不能在C中聲明char數組的三位數以上的數組?

[英]Why can't i declare a more than three digits array of array of char in C?

我正在編寫一個程序,該程序需要一個整數,然后使char數組組成數組,並找到所有行中每個char每次出現的次數。 該二維數組的大小為“ lineNumber”。 代碼如下所示。 問題是,當我獲得超過3位數字的輸入時,它停止工作並退出。 我真的發現問題在於聲明了chars數組。 你能告訴我如何克服這個問題嗎? 例如我想輸入1000行? 問題不在於scanf函數,我知道。 你能解決我的代碼嗎?

printf("Number of lines: ");
int lineNumber;
int n = scanf("%d", &lineNumber);
if (n == 0) {
   puts("Use integers.");
   return n;
}
char lines[lineNumber][1024]; /* It can't declare more than 3 digit integer */
int i = 0;
for (;i < lineNumber; i++) {
   printf("%d: ", i+1);
   fgets(lines[i], 1024, stdin);
   lines[i][strlen(lines[i])-1] = '\0';
}

/* count the number of occurrence of every char in all lines */

如果lineNumber例如是9000

char lineptr[lineNumber][1024];

那么lineptr使用大約9000*1024 = 9MB的堆棧空間。 根據您的操作系統和系統配置,這可能會使您的程序崩潰太多。 堆棧空間通常是有限的。

如果需要大量空間,最好使用malloc()分配內存。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM