Implementation of sequence table--dynamic allocation

#include <stdlib.h>
 #define initSize 10 // default maximum length 
typedef struct {
     int * data;
     int maxSize; // maximum capacity of sequence table 
    int length; // current length 
} SqList;
 void InitList (SqList & L) { 
    L.data = ( int *) malloc (initSize * sizeof ( int )); 
    L.length = 0 ; 
    L.maxSize = initSize; 
} 
// Increase the length of the dynamic array 
voidIncreaseSize (SqList & L, int len) {
     int * p = L.data; 
    L.data = ( int *) malloc ((L.maxSize + len) * sizeof ( int ));
     for ( int i = 0 ; i < L.length; i ++ ) { 
        L.data [i] = p [i]; 
    } 
    L.maxSize = L.maxSize + len;
     free (p); // Release the original memory space 
}
 int main () { 
    SqList L; 
    initList (L); 
    // ..... casually insert several elements 
    IncreaseSize (L,5 );
     return  0 ; 
} #include <stdlib.h>
 #define initSize 10 // default maximum length 
typedef struct {
     int * data;
     int maxSize; // maximum capacity of sequence table 
    int length; // current length 
} SqList;
 void InitList (SqList & L) { 
    L.data = ( int *) malloc (initSize * sizeof ( int )); 
    L.length = 0 ; 
    L.maxSize = initSize; 
}
 // Increase the length of the dynamic array 
void IncreaseSize (SqList & L, int len) {
     int * p = L.data; 
    L.data = ( int *) malloc ((L.maxSize + len) * sizeof ( int ));
     for ( int i = 0 ; i <L.length; i ++ ) { 
        L.data [i] = p [i]; 
    } 
    L.maxSize = L.maxSize + len;
     free (p); // Release the original memory space 
}
 int main () { 
    SqList L; 
    initList (L); 
    //..... casually insert a few elements 
    IncreaseSize (L, 5 );
     return  0 ; 
}

The malloc function applies for a continuous storage space and returns a pointer (the starting address of a whole continuous space) to data

So the data pointer now points to the starting address

Define the pointer p and assign the value of the data pointer to p, that is, the p pointer also points to the starting address of the continuous space

The data pointer points to the new memory space

free(p) #

Guess you like

Origin www.cnblogs.com/ikigai18/p/12708760.html