1

Is there a way in C to know how many values are in an array initialized like this?

char *string_array[] = {"one", "two", "three"};

Obviously there are three strings in the array but how can I determine the size at run time?

Jeff Melton
  • 357
  • 4
  • 13
  • Maybe this answer can help you? http://stackoverflow.com/a/37539/3048692 – TurboTheunis Mar 25 '14 at 13:02
  • Something like `sizeof(string_array)/sizeof(char)`? – Paulo Bu Mar 25 '14 at 13:02
  • This would give you the result sizeof(string_array)/sizeof(string_array[0]) – Mantosh Kumar Mar 25 '14 at 13:04
  • 1
    @PauloBu No, that would be wrong. Use sizeof(string_array)/sizeof(string_array[0]) – nos Mar 25 '14 at 13:04
  • 3
    Be careful when doing the trick provided in the possible duplicates answer, because it only works with the actual array. Once you pass an array as an argument to a function it decays to a pointer, and the trick will no longer work as the size of a pointer is the size of the pointer and not what it points to. – Some programmer dude Mar 25 '14 at 13:05
  • @nos I see that's better but in this case wouldn't they return the same? (Just a doubt) – Paulo Bu Mar 25 '14 at 13:05
  • @PauloBu no, the array elements are char pointers, not a char. sizeof(string_array)/sizeof(char*) would be correct too. – nos Mar 25 '14 at 13:07
  • @nos Argh, missed that, so silly. Thanks for clarifying! – Paulo Bu Mar 25 '14 at 13:18
  • Why would you need this information "at runtime", when it is patently available at compile time already? – Kerrek SB Mar 25 '14 at 13:18

0 Answers0