Re: determining size of array of chars



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

.



Relevant Pages

  • Re: Warning on assigning a function-returning-a-pointer-to-arrays
    ... This declares pfunc as a function taking no arguments and returning ... int x, y; ... Presumably pfuncwill return a pointer to a single int, ... or the first of a sequence of "array 5 of int"s. ...
    (comp.lang.c)
  • Re: The question regarding type of pointers
    ... int day_of_year ... According to my understanding daytab is pointing to the whole daytab ... array i.e it is equivalent to p3. ... daytab is converted to a pointer to the first ...
    (comp.lang.c)
  • Re: How would you design Cs replacement?
    ... I would get rid of void. ... a member called size of type int. ... size of the array pointed at by v->dynamic is given by int size. ... If you pass an unsized pointer to a sized parameter, ...
    (comp.lang.c)
  • Re: Newbie
    ... to talk about the int value 3 and the int value 4, ... It also lets you talk about pointer ... C has a special rule for array objects. ... to printf() is: ...
    (comp.lang.c)
  • Re: union {unsigned char u[10]; ...}
    ... But character type is not a union. ... u.a is of type int. ... has to do so to make pointer equality work consistently). ... were a single-element array. ...
    (comp.lang.c)