嵌入式筆試刷題(第27天)
1. C 和 C++ 中 struct 的區(qū)別?struct 和 class 的區(qū)別?
- 在 C 中: struct 僅用于定義數(shù)據(jù)結構,不能包含成員函數(shù)。struct 變量聲明必須使用 struct 關鍵字。
- 在 C++ 中: struct 可以包含成員函數(shù)、構造函數(shù)、析構函數(shù)、訪問控制(public/private)。默認訪問權限為 public,而 class 默認是 private。
示例:
struct A { int x; void print() { std::cout << x << std::endl; } }; class B { int x; // 默認為 private };
2. volatile 的含義與示例
volatile
告訴編譯器:該變量可能會被外部事件(如中斷、線程)修改,禁止優(yōu)化訪問。
三個例子:
// 例1:中斷標志 volatile int flag; void ISR() { flag = 1; } // 例2:多線程共享變量 volatile bool ready = false; // 例3:直接訪問硬件寄存器 #define REG (*(volatile unsigned int*)0x12345678)
3. 代碼問題分析與輸出結果
int main() { char a; char *str = &a; strcpy(str, "hello"); // 未分配足夠內(nèi)存 printf(str); // 格式字符串漏洞 return 0; }
問題:
str
指向一個字符(1字節(jié)),但strcpy
要寫入6字節(jié),造成內(nèi)存越界。printf(str);
使用不安全(格式字符串攻擊風險)。- 修正:
char str[10]; strcpy(str, "hello"); printf("%s", str);
4. 良好的編程習慣
- 使用有意義的命名。
- 編寫注釋、文檔。
- 控制變量作用域。
- 減少全局變量。
- 遵守編碼規(guī)范。
- 定期重構,消除代碼重復。
- 單一職責函數(shù)。
- 使用版本控制。
- 寫單元測試。
5. 輸出 1000~2000 閏年,每3個換行
規(guī)則:能被4整除但不能被100整除,或能被400整除。
#include <stdio.h> int main() { int count = 0; for (int year = 1000; year <= 2000; year++) { if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
剩余60%內(nèi)容,訂閱專欄后可繼續(xù)查看/也可單篇購買
嵌入式筆試專欄 文章被收錄于專欄
本專欄系統(tǒng)整理了嵌入式方向筆試中常見的知識點和高頻考題,涵蓋基礎理論、常用算法、C語言陷阱、操作系統(tǒng)原理、驅動開發(fā)、常見外設通信協(xié)議(如 I2C/SPI/UART)、RTOS、Linux 內(nèi)核、以及實用電路知識等內(nèi)容。