Skip to main content
added 73 characters in body
Source Link
sharptooth
  • 171.4k
  • 110
  • 545
  • 1k

Yes,

intsize_t n = sizeof(tbl) / sizeof(tbl[0]) 

is the most typical way to do this.

Please note that using int for array sizes is not the best idea.

Yes,

int n = sizeof(tbl) / sizeof(tbl[0]) 

is the most typical way to do this.

Yes,

size_t n = sizeof(tbl) / sizeof(tbl[0]) 

is the most typical way to do this.

Please note that using int for array sizes is not the best idea.

Rollback to Revision 1
Source Link
Keith Thompson
  • 265.6k
  • 46
  • 447
  • 668

Yes,

int n = sizeof(tbl) / sizeof(tbl[0]) 

is the most typical way to do this. An optimization would be to change it instead to:

int n = sizeof(tbl) / sizeof(char) 

At compile time, the sizeof(char) will be converted to a constant, saving you a de-referencing operation.

Also, take note that sizeof() will NOT work as expected if you pass the pointer tbl to a function, due to pointer decay.

References:


  1. How can I detect the size of an array passed as parameter?

Yes,

int n = sizeof(tbl) / sizeof(tbl[0]) 

is the most typical way to do this. An optimization would be to change it instead to:

int n = sizeof(tbl) / sizeof(char) 

At compile time, the sizeof(char) will be converted to a constant, saving you a de-referencing operation.

Also, take note that sizeof() will NOT work as expected if you pass the pointer tbl to a function, due to pointer decay.

References:


  1. How can I detect the size of an array passed as parameter?

Yes,

int n = sizeof(tbl) / sizeof(tbl[0]) 

is the most typical way to do this.

added 476 characters in body
Source Link
Cloud
  • 19.5k
  • 16
  • 96
  • 161

Yes,

int n = sizeof(tbl) / sizeof(tbl[0]) 

is the most typical way to do this. An optimization would be to change it instead to:

int n = sizeof(tbl) / sizeof(char) 

At compile time, the sizeof(char) will be converted to a constant, saving you a de-referencing operation.

Also, take note that sizeof() will NOT work as expected if you pass the pointer tbl to a function, due to pointer decay.

References:


  1. How can I detect the size of an array passed as parameter?

Yes,

int n = sizeof(tbl) / sizeof(tbl[0]) 

is the most typical way to do this.

Yes,

int n = sizeof(tbl) / sizeof(tbl[0]) 

is the most typical way to do this. An optimization would be to change it instead to:

int n = sizeof(tbl) / sizeof(char) 

At compile time, the sizeof(char) will be converted to a constant, saving you a de-referencing operation.

Also, take note that sizeof() will NOT work as expected if you pass the pointer tbl to a function, due to pointer decay.

References:


  1. How can I detect the size of an array passed as parameter?
Source Link
sharptooth
  • 171.4k
  • 110
  • 545
  • 1k
Loading