0

Is there any inbuilt function in cpp that can give me the length of a 2d char array

for ex, the function for args

const char* args[] = {"412", "..7", ".58", "7.8", "32.", "6..", "351", "3.9", "985", "...", ".46"}

should return 11

4
  • There is no actual function, since using an array as a function parameter causes it to decay to a pointer. The macros given in the answers can be used in the array's scope. Commented Feb 9, 2012 at 22:19
  • @David: arrays don't decay if you pass by reference. Commented Feb 9, 2012 at 22:21
  • If you want to do something like that in an idiomatic C++ program, it's more like std::vector<std::string> rather than a char *args[]. That way, you do get functions that work. Commented Feb 9, 2012 at 22:21
  • Even though the question is narrowly focused on 2d string array, the answer by R. Martinho Fernandes has much wider application to arrays in general. How about editing the title to ask the general question "Function to find length of array in C++?" so the question can be voted up and get more exposure? Commented Feb 10, 2012 at 4:55

4 Answers 4

7

I like to use a template function for this.

template <typename T, std::size_t N>
std::size_t size(T(&)[N]) { return N; }

The advantage over an approach using sizeof is that you can't accidentally do it with a pointer.

Sign up to request clarification or add additional context in comments.

3 Comments

Bah, you and your fancy template stuff :)
+1 Specifically, this version fails to compile when passed a pointer. The alternative, sizeof A/sizeof A[0], returns the wrong number when passed a pointer. Failing to compile is always better than giving the wrong answer.
I tried sizeof(args)/sizeof(args[0]); and it works :) I didn't want to go for templates, I don't know how to Initialize a 2d string array in them.
4

This will give the number of elements in args:

sizeof(args) / sizeof(args[0])

1 Comment

And I'd note that even if you go for one of the other new-fangled ways listed, you should remember this idiom as you'll come across it in a ton of old C++ and C code.
2

In C++11 you can use:

std::end(args) - std::begin(args)

Comments

1

sizeof(args) / sizeof(*args)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.