当然,以下是十个关于 C 语言用法的代码示例:
- 指针的基本用法:
#include <stdio.h>int main() {int num = 10;int *ptr;ptr = #printf("The value of num is: %d\n", *ptr);return 0;
}
- 结构体的使用:
#include <stdio.h>struct Person {char name[50];int age;
};int main() {struct Person person1;strcpy(person1.name, "Alice");person1.age = 30;printf("Person: %s, Age: %d\n", person1.name, person1.age);return 0;
}
- 文件操作:
#include <stdio.h>int main() {FILE *file;file = fopen("example.txt", "w");if (file) {fprintf(file, "Hello, C programming!");fclose(file);}return 0;
}
- 动态内存分配:
#include <stdio.h>
#include <stdlib.h>int main() {int *ptr;ptr = (int *) malloc(sizeof(int));*ptr = 42;printf("Value: %d\n", *ptr);free(ptr);return 0;
}
- 函数指针:
#include <stdio.h>void printHello() {printf("Hello, C!\n");
}int main() {void (*funcPtr)() = &printHello;funcPtr();return 0;
}
- 预处理指令:
#include <stdio.h>#define PI 3.14159int main() {float radius = 5.0;float area = PI * radius * radius;printf("Area of circle: %.2f\n", area);return 0;
}
- 位运算:
#include <stdio.h>int main() {int num = 5; // binary: 101int result = num & 3; // 3 in binary is 011printf("Result: %d\n", result);return 0;
}
- 多级指针:
#include <stdio.h>int main() {int num = 42;int *ptr = #int **ptrPtr = &ptr;printf("Value: %d\n", **ptrPtr);return 0;
}
- 递归:
#include <stdio.h>int factorial(int n) {if (n == 0) {return 1;}return n * factorial(n - 1);
}int main() {int num = 5;printf("Factorial of %d is %d\n", num, factorial(num));return 0;
}
- Printf 和 Scanf 格式化输出:
#include <stdio.h>int main() {int num;printf("Enter a number: ");scanf("%d", &num);printf("You entered: %d\n", num);return 0;
}
这些代码示例展示了 C 语言中一些常见用法的实