C sizeof char* array

…衆ロ難τιáo~ 提交于 2019-11-27 12:49:08

问题


I have a char* array as follows:

char *tbl[] = { "1", "2", "3" };

How do I use the sizeof operator to get the number of elements of the array, here 3?

The below did work, but is it correct?

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

回答1:


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.




回答2:


The shorter and, arguably, cleaner version would look as

sizeof tbl / sizeof *tbl

:)




回答3:


Yes, it will give you the number of elements in the array tb1.

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

Interpretation:

sizeof(tb1) will gives the size of the entire array i.e, tb1 = 3 bytes

sizeof(tb1[0]) gives the size of the character as tb1[0] gives a character value(value at address tb1+0) = 1 byte

Division of those two will give you 3 elements



来源:https://stackoverflow.com/questions/1559925/c-sizeof-char-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!