C語言變長數組

來源:互聯網
上載者:User
C語言變長數組

我們知道,傳統的C語言是不能像C++那樣支援變長數組的,也就是說數組的長度是在編譯期就確定下來的,不能在運行期改變。C99標準定義的C語言新特性,新增的一項功能可以允許在C語言中使用變長數組。

C99 gives C programmers the ability to use variable length arrays, which are arrays whose sizes are not known until run time. A variable length array declaration is like a fixed array declaration except that the array size is specified by a non-constant expression. When the declaration is encountered, the size expression is evaluated and the array is created with the indicated length, which must be a positive integer. Once created, variable length array cannot change in length. Elements in the array can be accessed up to the allocated length; accessing elements beyond that length results in undefined behavior. There is no check required for such out-of-range accesses. The array is destroyed when the block containing the declaration completes. Each time the block is started, a new array is allocated.


以上就是C99標準對C語言變長數組的說明.

C語變長數組,測試所用的原始碼很簡單,如下所示:

  1. //檔案名稱:dynarray.c
  2. //編譯環境: bloodshed dev-c/c++ 4.9
  3. #include <stdio.h>
  4. #define bzero(b,len) (memset((b), '/0', (len)), (void) 0)

  5. int main(int argc, char *argv[])
  6. {
  7.   int i, n;

  8.   n = atoi(argv[1]);
  9.   
  10.   char arr[n+1];
  11.   bzero(arr, (n+1) * sizeof(char));

  12.   for (i = 0; i < n; i++) {
  13.     arr[i] = (char)('A' + i);
  14.   }
  15.   arr[n] = '/0';
  16.   printf("%s/n", arr);

  17.   getchar();
  18.   return (0);

  19.  }

上述程式名為dynarray.c,其工作是把參數argv[1]的值n加上1作為變長數組arr的長度,變長數組arr的類型為char。然後向數組中寫入一些字元,並將寫入的字串輸出。

在支援c99標準的IDE上編譯後, 在命令提示字元下,運行: 

c:/c99_test/dynarray.exe 6

將輸出: 

ABCDEF


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.