# C Primer Plus ## Pointer ```c= int main(int argc, char **argv) { int * pi; //pi is a pointer to integer variable char * pc; //pc is a pointer to char variable } int main(int argc, char **argv) { int ref[4] = {8,4,0,2}; int *ptr,index; for(index=0,ptr = ref;index<4;index++,ptr++) printf("%d %p %p\n",*ptr,ptr,&ptr); // value ; point-to-address ; address of pointer itself } ``` ### Use pointer to exchange ```c= #include <stdio.h> #include <ctype.h> #include <stdbool.h> void interchange(int * u, int * v); int main(int argc, char **argv) { int x=5,y=10; interchange(&x,&y); printf("%d",x); } void interchange(int * u, int * v) { int temp; temp = *u; *u = *v; *v = temp; } ``` ### Point to multiDimensional array ```c= // This is an example of declartion int (* pz)[2]; // pz points to a two-dimension array int * pz[2]; // pz is an array of two pointer-to-int // Deal with two dimension array int sum2d(int ar[][COLS]); int main(int argc, char **argv) { int ar[3][COLS] = { {1,2,3,4}, {5,6,7,8}, {9,1,6,5} }; printf("%d",sum2d(ar)); } int sum2d(int (* ar)[COLS]) { int sum = 0; for(int i=0;i<3;i++) { for(int j=0;j<COLS;j++) { sum+= (*(ar+i))[j]; printf("%d ",(*(ar+i))[j]); } printf("\n"); } return sum; } ``` ```c= // Compound literal // use pointer to keep track of the compund literal declaration int main(int argc, char **argv) { int * p; p = (int [2]) {10,20}; // same as int ar[2] = {10,20}; printf("%d", *p++); } ``` ## String ### Some library ```c= // this library is for char array #include <ctype.h> // The ctype.h header file of the C Standard // Library declares several functions // that are useful for testing and mapping characters. char str[]; strlen(str); // return the length of string strcat(str); // concantate two string and delare to fore one strcmp(str1,str2); // compare two string , 0 match , !=0 unmatch strcpy(str1,str2); // copy the string to fore one ``` ### sprintf ```c= int main(int argc, char **argv) { char str1[10] = "hello"; char str2[5] = "ncku"; char full[50]; sprintf(full, "%7s I am Li from %6s" , str1 , str2); puts(full); // hello I am Li from ncku } ``` ## Structure ### Allocate memory ```c= struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode)); ``` ### Via pointer ```c= struct name{ char firstName[]; char lastName[]; } int main(int argc,char **argc) { struct name person = { "Chen Wei", "Li" }; struct name * ptr = &person; } ``` ### Pass value ```c= struct fund{ int value; } // use a constant pointer points to a structure int sum(const struct fund * ptr); ``` ## Bit ```c= /* * reverse a uint32_t value */ uint32_t reverseBits(uint32_t n) { uint32_t bits[32]; uint32_t bin = 1; //0b00000000000000000000000000000001 uint32_t ret = 0; // store all of the mask and reverse the mask for(int i=0;i<32;i++){ bits[i] = (n&(bin<<i))>>i; bits[i] <<= (31-i); ret |= bits[i]; } return ret; } /* * 改良版 */ uint32_t reverseBits(uint32_t n) { uint32_t bin = 1 , ret = 0; for(int i=0;i<32;i++){ ret |= ((n & (bin << i)) >> i ) << (31-i); } return ret; } ``` ## Sort ```c= #include <stdio.h> #include <stdlib.h> void fillarray(double ar[], int n); void showarray(const double ar[], int n); int mycomp(const void* p1,const void * p2); int main(int argc, char **argv) { double vals[10]; fillarray(vals,10); showarray(vals,10); qsort(vals,10,sizeof(double),mycomp); showarray(vals,10); } void fillarray(double ar[], int n) { int index; for(index = 0;index < n;index++) ar[index] = (double)rand() / ((double)rand() + 0.1); } void showarray(const double ar[],int n) { int index; for(index=0;index < n;index++) { printf("%9.4f",ar[index]); } putchar('\n'); } int mycomp(const void * p1, const void * p2) { const double * a1 = (const double *) p1; const double * a2 = (const double *) p2; if(*a1 > *a2) // > 降序 , < 升序 return -1; else if(*a1 == *a2) return 0; else return 1; } /* * * long long 長整數排序 * */ int _cmp(const void * a, const void * b) { if( *(long long int*)a - *(long long int*)b < 0 ) return -1; if( *(long long int*)a - *(long long int*)b > 0 ) return 1; return 0; } /* * 簡化版 mycomp * 升序排列 */ static int _cmp(const int *l,const int *r){ return (*l - *r); } ``` ### Merge sort ![](https://i.imgur.com/D2c1Rh9.gif) ### Heap sort ![](https://i.imgur.com/fi2uJ94.gif) 先將數組按binary tree順序放入堆疊中,若比父母節點大則向上移動 接著從根結點開始拿取,拿完和最右葉節點做交換,然後將此節點向下做排序(找大的)跟他換 ### Quick sort ![](https://i.imgur.com/tGplB7r.gif) ```c= // Quick sort in C #include <stdio.h> // function to swap elements void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; } // function to find the partition position int partition(int array[], int low, int high) { // select the rightmost element as pivot int pivot = array[high]; // pointer for greater element int i = (low - 1); // traverse each element of the array // compare them with the pivot for (int j = low; j < high; j++) { if (array[j] <= pivot) { // if element smaller than pivot is found // swap it with the greater element pointed by i i++; // swap element at i with element at j swap(&array[i], &array[j]); } } // swap the pivot element with the greater element at i swap(&array[i + 1], &array[high]); // return the partition point return (i + 1); } void quickSort(int array[], int low, int high) { if (low < high) { // find the pivot element such that // elements smaller than pivot are on left of pivot // elements greater than pivot are on right of pivot int pi = partition(array, low, high); // recursive call on the left of pivot quickSort(array, low, pi - 1); // recursive call on the right of pivot quickSort(array, pi + 1, high); } } // function to print array elements void printArray(int array[], int size) { for (int i = 0; i < size; ++i) { printf("%d ", array[i]); } printf("\n"); } // main function int main() { int data[] = {8, 7, 2, 1, 0, 9, 6}; int n = sizeof(data) / sizeof(data[0]); printf("Unsorted Array\n"); printArray(data, n); // perform quicksort on data quickSort(data, 0, n - 1); printf("Sorted array in ascending order: \n"); printArray(data, n); } ``` ### HASH ```c // UT_hash_handle 為必要聲明 struct hash_struct { int id; int value; UT_hash_handle hh; }; bool containsNearbyDuplicate(int* nums, int numsSize, int k){ // 建立空哈希表 struct hash_struct *map = NULL; for(int i = 0 ; i < numsSize ;i++) { struct hash_struct *tmp; // 第二個參數一定要傳遞地址 HASH_FIND_INT(map, &nums[i], tmp); if(tmp == NULL) { // 宣告空間並賦值 tmp = (struct hash_struct*)malloc(sizeof(struct hash_struct)); tmp->id = nums[i]; tmp->value = i; // 第二個參數添加鍵字段名稱 id HASH_ADD_INT(map, id, tmp); } else { if((i - tmp->value) <= k) return true; else tmp->value = i; } } return false; } ``` ## Terms - VLA The length of an array is determined during run-time (not compile time) - ## Some Questions - How const works? A pointer can change the value of const array.