|
温故而知新
1.函数指针
#include <stdio.h>
int max(int x, int y)
{
return x > y ? x : y;
}
int main()
{
int (* p)(int, int) = & max;
int a, b, c, d;
printf("请输入三个数字:");
scanf("%d %d %d", & a, & b, & c);
d = p(p(a, b), c);
printf("最大的数字是: %d\n", d);
return 0;
}
回调函数
#include <stdlib.h>
#include <stdio.h>
void populate_array(int *array, size_t arraySize, int (*getNextValue)(void))
{
for (size_t i=0; i<arraySize; i++)
array[i] = **getNextValue**();
}
int **getNextRandomValue**(void)
{
return rand();
}
int main(void)
{
int myarray[10];
populate_array(myarray, 10, **getNextRandomValue**);
for(int i = 0; i < 10; i++) {
printf("%d ", myarray[i]);
}
printf("\n");
return 0;
}
等价函数
#include <stdlib.h>
#include <stdio.h>
int getNextValue(void)
{
return rand();
}
void populate_array(int *array, size_t arraySize)
{
for (size_t i=0; i<arraySize; i++)
array[i] = getNextValue();
}
int main(void)
{
int myarray[10];
populate_array(myarray, 10);
for(int i = 0; i < 10; i++) {
printf("%d ", myarray[i]);
}
printf("\n");
return 0;
}
2.结构体
指向结构的指针
#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
void printBook( struct Books *book );
int main( )
{
struct Books Book1;
struct Books Book2;
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
printBook( &Book1 );
printBook( &Book2 );
return 0;
}
void printBook( struct Books *book )
{
printf( "Book title : %s\n", book->title);
printf( "Book author : %s\n", book->author);
printf( "Book subject : %s\n", book->subject);
printf( "Book book_id : %d\n", book->book_id);
}
3.共用体
节省内存,同一时间只用一个成员
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %s\n", data.str);
return 0;
}
//
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);前两个变量值会被破坏
4.位域
struct k{
int a:1;
int :2;
int b:3;
int c:2;
};
struct
{
unsigned int widthValidated : 1;
unsigned int heightValidated : 1;
} status;
|