I am trying to implement a command line interface function for a micro-controller, which has very limited stack size (around 1kB) and I do not want to use an array to hold the string values to not push them into the stack. I come up with two solutions, but according to the coding standard, I should not use #define in the function definition.
How can I use strings along with sizeof operator without using #define and arrays?
#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;
}
CodePudding user response:
Make the arrays static
so they will not be allocated on the stack.
static const char fetch[] = "fetch";
static const char push[] = "push";
static const char quit[] = "quit";