const char *
const char * str = "Hello World\n";
printf ("%s\n", str);
char str[] = "Hello world\n";
char str[] = {'H', 'e', ..., '\n', '\0'};
char* strcpy (char* dest, const char* src);
double myMatrix[4][3];
myMatrix[2][1]
), this expression can be a lvaluemyMatrix[2]
)Example:
1
2
3
4
double myMatrix[4][3] = { {1,2,3},
{7,8,9},
{2,4,8},
{5,6,7}};
Example:
1
2
3
4
double row0[3];
double row1[4];
double row2[2];
double * myMatrix[3] = {row0, row1, row2};
char str[3][4] = {"Abd","def",“ghi”};
char chrs[3][3] = {"Abc","def","ghi"}
const char * words[] = {"A", "cat", "likes",NULL};
Application:
Create a function pointer as a parameter to a function we are writing. We can apply this to eliminate the similar functions by creating a function table. We can also apply function pointer to call back functions.
Example:
c
void doToAll(int * data, int n, int (*f)(int)) {
for (int i = 0; i < n; i++) {
data[i] = f(data[i]);
}
}
[!Tip]
When defining a function pointer type, we should wrap the name with*
and()
like(*name)
, but when passing it to another function, we don’t need*
If we don’t define a function pointer type and directly pass a function pointer, we should add
*
when employing it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//Define a function pointer
void (*Func_ptr) (int);
//Or we can define by typedef, it is equivalent
typedef void (*Func_ptr) (int);
//Define a function that matches the function pointer
void print_Func (int value){
printf("%d", value);
}
//Define a function that takes a function pointer
void exe_func (Func_ptr pass_func, int arg){
pass_func(arg);
}
int main(){
exe_func (print_Func, 42);
return;
}
Sorting elements Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//Now we implement a sort operation on a general kind of data
//Specify the is_smaller function before
//Input: base: pointers to the array, n_elts: number of array elements, size: number of bytes per thing, function pointer
//Return value: 1 on success, 0 on failure
int32_t isort(void* base, int32_t n_elts, size_t size, int32_t (*is_smaller) (void* t1, void* t2))
{
//declare some local variables
char* array = base;
void* current;
int32_t sorted; //indicate the sorted element
int32_t index; //indicate the comparison index
//Different kinds of data have different size -> dynamically allocate the size
if (NULL == (current = malloc(size))){
return 0;
}
for(sorted = 2; sorted <= n_elts; sorted++){
//copy the current thing for comparison
memcpy(current, array + (sorted-1)*size, size)
//inner loop for comparison
for(index = sorted-1; 0 < index; index--){
if ((*is_smaller)(current, array + (index-1)*size)){
//move the comparison object to the right
memcpy(array + index*size, array + (index-1)*size, size);
}else{
break;
}
}
//find the right place
memcpy(array + index*size, current, size);
}
free (current);
return 1;
}
*find = p->next
free (p->name);
free (p);`