hi, i need help.. i have been working for about 4 hours trying to figure this out and im still lost.. the answer is probably simple but im new to c++ so please forgive me. off a site called informit, the following code is posted:

#define NELEMS(A) (sizeof(A) / sizeof A[0])

 struct math {
  const char *name;       // name of math function
  double (*pmf)(double);     // ptr to math function
 };

 math mtab[] = {          // dispatch table
  "sin", sin,
  "cos", cos,
  "exp", exp,
  "tan", tan,
  "sqrt", sqrt
 };

//NELEMS(mtab) returns 5

"The NELEMS macro determines the number of elements in dispatch table mtab"

i can compile that code and the NELEMS macro function works without any problems. i tried rewriting some of the code in a program i have and im having issues determining the number of elements in mtab when i use the NELEMS function with a pointer from a class function where the structure member (mtab) is referenced.

//math *smath;
//myclass->smath points to mtab
(sizeof(myclass->smath) / sizeof(myclass->smath[0])

which returns 0 no matter what i do (i have 3 elements listed so it should be returning 3), i have no idea what im doing wrong.. if anyone can help id really appreciate it, thanks

The first piece of code works because "mtab" is an statically-sized array which the compiler knows the size at compile time. (The macro is just a convenient compile-time trick.) The second piece of code doesn't work because "myclass->smath" is a pointer, and there is no way to tell how many things are in an array at runtime if you only know where the first element is. Arrays and pointers are not the same.

The first piece of code works because "mtab" is an statically-sized array which the compiler knows the size at compile time. (The macro is just a convenient compile-time trick.) The second piece of code doesn't work because "myclass->smath" is a pointer, and there is no way to tell how many things are in an array at runtime if you only know where the first element is. Arrays and pointers are not the same.

thanks for your reply, that makes sense. so what do you think the best solution for me would be to do? because i need to determine how many elements are in the array, im not sure what would be the most effecient wait to go about doing this

If you are passing smath to a function then you will also have to pass the number of elelemts, because there is no way for the function to get the number of elements from just a pointer. sizeof(any pointer here) in 32-bit compilers is always 4. sizeof(struct math) is 8. and 4/8 = 0.

This article has been dead for over six months. Start a new discussion instead.