Generic pair in C99
typedef struct pairX{
void* x;
void* y;
} pairX;
pairX* pt = (pairX*)malloc(sizeof(pairX));
int a = 1;
int b = 4;
pt -> x = (int*)&a;
pt -> y = (int*)&b;
printf("x=%d\n", *(int*)(pt -> x));
printf("y=%d\n", *(int*)(pt -> y));
free(pt);
Assign an array to void* x
typedef struct pairX{
void* x;
void* y;
} pairX;
const int len = 4;
pairX* pt = (pairX*)malloc(sizeof(pairX));
int arr[len] = {1, 2, 3, 4}; // DO NOT need to free this
int b = 10;
pt -> x = (int*)arr;
pt -> y = (int*)&b;
print_array_int(pt -> x, len, len);
printf("pt -> y = %d\n", *(int*)(pt -> y));
free(pt);
return a struct from a function
typedef struct pair{
int x;
int y;
} pair;
pair fun(int a, int b){
pair p;
p.x = a;
p.y = b;
return p;
}
const int* pt and int* const pt
const int* pt;
pt = (int*) malloc(sizeof(int) * 4);
pt[0] = 10; // ERROR
int arr[4] = {10, 20, 30, 40};
pt = arr; // OK
void fun(const int* pt){
}
int arr[4];
fun(arr); // OK
int* const pt;
pt += 1; // ERROR
char, unsigned char, signed char in C
char type in C is 8 bits, integer type, it has minimum range from 0 to 127
char can be unsigned or signed
unsigned char range: 0000 0000 → 1111 1111 → 0x00 0xFF → 0 to 2^8 ⇒ 0 to 255
signed char range: 0000 0000 → 1xxx xxxx → 0xxx xxxx → [-2⁷ → -1] [0 → 2⁷ - 1]
Conver integer, float to string
const int size = 100;
char buf[size];
int num = 10;
float pi = 3.1415;
snprintf(buf, size, "%d-%f", num, pi);
C struct
struct my_stuff_{
int n;
char name[100];
} my_stuff_;
typedef struct my_stuff_ my_stuff;
my_stuff* pt = (my_stuff*)malloc(sizeof(my_stuff));
pt -> n = 10;
strcpy(pt -> name, "abcde fghij klmno pqrst uwwxy z");
free(pt);
Pass C function as argument to a function
int myfun(int(*funpt)(int, int)){
int sum = 0;
for(int i = 0; i < 3; i++){
sum += (*funpt)(i, i);
}
return sum;
}
int add(int a, int b){
return a + b;
}
int num = myfun(add);
// how to pass paramter from outside to add
// int a=1, b=2; add(a, b)
funpt is function pointer, (*funpt) is a function which have two parameters: int, int and return type is int. myfun only accept function pointer has the same signature, otherwise there is compiling error.
Pass function to a function pointer
In order to assign a function to other function pointer. *funpt and add both have to have the same signature.
int(*funpt)(int, int);
int addMe(int a, int b){
return a + b;
}
funpt = &addMe;
printf("num=%d\n", (*funpt)(1, 2));
printf("funpt=x%x\n", funpt);
printf("&add=x%x\n", &addMe);
C++ unique_ptr, C++ Smart pointer
template<typename T1, typename T2>
class MyTuple{
public:
T1 x;
T2 y;
public:
MyTuple<T1, T2>(){
}
MyTuple<T1, T2>(T1 t1, T2 t2){
x = t1;
y = t2;
}
};
unique_ptr<MyTuple<int, int>> tuplept(new MyTuple<int, int>(1, 2));
cout<<"x="<<tuplept -> x<<endl;
cout<<"y="<<tuplept -> y<<endl;