Re: determining size of array of chars
- From: David Resnick <lndresnick@xxxxxxxxx>
- Date: Mon, 23 Aug 2010 08:16:53 -0700 (PDT)
On Aug 23, 11:10 am, "Francesco S. Carta" <entul...@xxxxxxxxx> wrote:
dehantonio <dehanto...@xxxxxxxxx>, on 23/08/2010 08:00:02, wrote:
On 23 Ago, 16:51, You're talkin 'bout China Blue Grove
<chine.b...@xxxxxxxxx> wrote:
This is an array of strings, not chars. A trick to get the length of an array A
is
(sizeof A/sizeof A[0])
provided A is actually an array and not a pointer.
In other words, it will not work with my code. Correct?
Said that, the answer is there is no way to get rid of the define in
my code?
It seems to work - caveat, I'm just starting with C, so cope with any
error of mine (but point them out if any, please):
#include <stdlib.h>
#include <string.h>
const char *LineMenu[] = {"ls", "pwd", "cd"};
int somefunction(char* inputbuffer) {
int idx;
const int menusize = sizeof(LineMenu) / sizeof(LineMenu[0]);
for (idx = 0; idx < menusize; idx++) {
if (strstr(inputbuffer, LineMenu[idx])) {
return idx;
}
}
//not found:
return -1;
}
int main(void) {
printf("%d\n", somefunction("cd"));
return 0;
}
This approach works as long as the array declaration is in scope.
Common ways to handle this if the array is NOT in scope -- which is
quite often the case -- include:
1) Pass around the array size. Either as a separate parameter, or
have a struct whose members are the array and its size.
2) Put a sentinel in the array. e.g. assuming that you'd never
actually want NULL pointer in your menu, put one at the end. You can
then process the array until the NULL is found and know you are done.
-David
.
- Follow-Ups:
- Re: determining size of array of chars
- From: Francesco S. Carta
- Re: determining size of array of chars
- References:
- determining size of array of chars
- From: dehantonio
- Re: determining size of array of chars
- From: dehantonio
- Re: determining size of array of chars
- From: Francesco S. Carta
- determining size of array of chars
- Prev by Date: Re: determining size of array of chars
- Next by Date: Re: determining size of array of chars
- Previous by thread: Re: determining size of array of chars
- Next by thread: Re: determining size of array of chars
- Index(es):
Relevant Pages
|