C and pointer Dynamic Array Implementation

Source: Internet
Author: User
/*  * C and pointer Chapter 2 the second question reads a series of integers from the standard input, stores these values in a dynamically allocated array, and returns this array. The first element of the array is the length of the array. Other elements are input integers.  */  # Include <Stdio. h> # Include <Stdlib. h> //  Define a length, which is allocated at the beginning  # Define Length 20 Int * Read_ints (){  Int * Num;  Int TEM;  Int Count = 0  ;  Int Size = Length;  //  Allocate memory Num = malloc (size + 1 )* Sizeof ( Int  ));  //  Memory Allocation failed, return null      If (Num =Null)  Return  NULL;  While (Scanf ( "  % D  " , & TEM )! = EOF) {count ++ ;  //  If the length is greater than the allocated memory, you need to increase the memory and use realloc for allocation.          If (Count> Size) {size + = Length; num = Realloc (Num, (size + 1 )* Sizeof ( Int  ));  If (Num = Null)  Return  NULL;} num [count] = TEM ;}  If (Count < Size) {num = Realloc (Num, (count + 1 )* Sizeof (Int  ));  If (Num = Null)  Return  NULL;} num [  0 ] = Count;  Return  Num ;}  Int  Main (){  Int * Array;  Int  I; Array = Read_ints ();  For (I = 1 ; I <= array [ 0 ]; I ++ ) Printf (  "  % D  "  , Array [I]);  Return   0  ;} 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.