我正在嘗試為微控制器實作命令列介面功能,該微控制器的堆疊大小非常有限(大約 1kB),我不想使用陣列來保存字串值而不將它們推入堆疊。我想出了兩個解決方案,但是根據編碼標準,我不應該在函式定義中使用#define。
如何在不使用 #define 和陣列的情況下使用字串和 sizeof 運算子?
#include <stdio.h>
#include <string.h>
#define ARRAY_COUNT(a) (sizeof(a)/sizeof(a[0]))
int cli(int argc, char *argv[])
{
#if 1
// I should not use #define in function definition due to the coding standard
#define fetch "fetch"
#define push "push"
#define quit "quit"
#else
// arrays get allocated in stack, and stack is very small
const char fetch[] = "fetch";
const char push[] = "push";
const char quit[] = "quit";
#endif
if (1 < argc) {
if (!strncmp(argv[1], fetch, ARRAY_COUNT(fetch)-1)) {
// do fetc...
} else if (!strncmp(argv[1], push, ARRAY_COUNT(push)-1)) {
// do push...
} else if (!strncmp(argv[1], quit, ARRAY_COUNT(quit)-1)) {
// do quit...
}
}
return 0;
}
uj5u.com熱心網友回復:
制作陣列static,使它們不會在堆疊上分配。
static const char fetch[] = "fetch";
static const char push[] = "push";
static const char quit[] = "quit";
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/516498.html
上一篇:如何洗掉此解決方案中的重復代碼?
