LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How do I get the number of elements in a char*[] in c++? (https://www.linuxquestions.org/questions/programming-9/how-do-i-get-the-number-of-elements-in-a-char%2A%5B%5D-in-c-858961/)

chinho 01-27-2011 03:06 AM

How do I get the number of elements in a char*[] in c++?
 
Hi guys,

I have a char*[] array:

Code:

char* myarray[] = {"Hello", "there!", "LQ"};
and I wish to use/ write a function to find the number of elements in myarray (in this case, its 3).

*equivalent of .NET's array.size() that returns number of elements in array

How do I achieve it?

Thanks in advance,
Chinho

truboy 01-27-2011 03:45 AM

Quote:

Originally Posted by chinho (Post 4239226)
How do I achieve it?

Hi,

Using [] makes a pure C array, so you will have to find the number of element "by yourself", with a loop and testing every position.

C++ has a type called vector, that allow some functions like size().

A basic declaration of a vector of int would be :
Code:

vector<int> example;
Read this for more information.

ForzaItalia2006 01-27-2011 01:24 PM

Quote:

Originally Posted by truboy (Post 4239255)
Hi,

Using [] makes a pure C array, so you will have to find the number of element "by yourself", with a loop and testing every position.

Hey truboy,

this is not completely true. You could also use the sizeof() operator for both; fixed-size and variable-size arrays. To be clear in the OP's case, sizeof() will not return 3, but the number of bytes occupied by the array, though on a 64-bit system, it would return 24. But you could then easily determine the real size by e.g.:

Code:

sizeof(myarray) / sizeof(myarray[0])
Note, that in sizeof(myarray[0]) the first element is not accessed, but the type of the first (and hence all elements) is considered.


BTW, I don't want to say that my approach should be used, especially in c++ which has a rich and great set of STL data structure/containers, but I just want to show the available possibilities ;-)

Andi

paulsm4 01-27-2011 03:00 PM

Hi -

Quote:

Q: I have a char*[] array ... [How can I] find the number of elements in myarray?
A: In general, you CAN'T.

If the specific array is in scope then, as ForzaItalia2006 pointed out, you can use the C/C++ "sizeof" operator.

Code:

#include <stdio.h>

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

char* myarray[] = {"Hello", "there!", "LQ"};

int
main (int argc, char *argv[])
{
  printf ("#/elements= %d...\n", NELMS(myarray));
  return 0;
}

Quote:

OUTPUT: #/elements= 3...
Or, as truboy pointed out, you can use a higher-level type, such as an STL "vector<>".

johnsfine 01-27-2011 03:34 PM

For the exact question asked, I think ForzaItalia2006 gave the correct answer:
Code:

sizeof(myarray) / sizeof(myarray[0])
But in context with chinho's related thread:

http://www.linuxquestions.org/questi...r-in-c-858967/

It is important to note that the given method of getting the element count only works with the original defined copy of myarray. Passing a char*[] into a function as a parameter makes it just another syntax for char**. On char** or equivalent, you cannot determine the element count.

Looking at both threads, I suspect the intent was to determine element count inside a function that received char*[] as a parameter. There is no decent answer to that. In C++ the best answer is don't try.

As others have already advised, instead use std::vector<char const*> or even std::vector<std::string>

The reason those exist is because of this sort of problem in C arrays and C strings.

z1p 01-27-2011 03:41 PM

Quote:

Originally Posted by johnsfine (Post 4239933)
For the exact question asked, I think ForzaItalia2006 gave the correct answer:
Code:

sizeof(myarray) / sizeof(myarray[0])
But in context with chinho's related thread:

http://www.linuxquestions.org/questi...r-in-c-858967/

It is important to note that the given method of getting the element count only works with the original defined copy of myarray. Passing a char*[] into a function as a parameter makes it just another syntax for char**. On char** or equivalent, you cannot determine the element count.

Looking at both threads, I suspect the intent was to determine element count inside a function that received char*[] as a parameter. There is no decent answer to that. In C++ the best answer is don't try.

As others have already advised, instead use std::vector<char const*> or even std::vector<std::string>

The reason those exist is because of this sort of problem in C arrays and C strings.

1st off vectors..good, array of strings...not so good. I think we all agree on that. ;)

If the intent is to pass the array as an argument, then the only options I see is to pass the number of elements along with it, or add a terminateing NULL pointer so that the calle can determine the end of the array by checking for a NULL pointer.

johnsfine 01-27-2011 04:03 PM

Quote:

Originally Posted by z1p (Post 4239945)
1st off vectors..good, array of strings...not so good. I think we all agree on that. ;)

I'm never that agreeable (personality defect maybe).

I probably have used C arrays of C quoted strings more often in C++ than I have used std::vector for similar purposes (obviously less often than I have used std::vector for other purposes). In the hands of an expert, a C array of C strings is easy to use and efficient and often the better choice. But it is never enough better to justify the mistakes or confusion it generates in the hands of a beginner.

Quote:

If the intent is to pass the array as an argument, then the only options I see is to pass the number of elements along with it, or add a terminateing NULL pointer so that the calle can determine the end of the array by checking for a NULL pointer.
Yeah sure, but anyone who needs that kind of advice shouldn't be using a C array of C strings in C++ at all. When there is no easier way, certainly tell the beginner the hard way. When someone has learned enough other stuff to justify doing things in what would originally have been the hard way, then start to tell them how to decide which is better. But in this thread, not.

Quote:

Originally Posted by z1p (Post 4239945)
1st off vectors..good, array of strings...not so good. I think we all agree on that. .

How about vectors.. good for beginners and often good for experts. Array of strings.. not as good for beginners.

paulsm4 01-28-2011 01:30 AM

Hi, again Chinho -

The point I tried to make above, and a message I think you're hearing loud and clear, is that when you're using C-style arrays ("raw pointers"), you can't always get the #/elements in that array. For example, if you pass "myarray" into a function, that function has absolutely NO way to know how many elements are in the array.

Unless, of course, you tell it ;)

It's a common idiom to simply pass the #/elements as an argument into your function, along with the array itself. Good examples include standard IO, and sockets:
Code:

      #include <stdio.h>

      size_t  fread(  void *ptr, size_t size, size_t nmemb, FILE
      *stream);

Code:

      #include <sys/types.h>
      #include <sys/socket.h>

      int send(int s, const void *msg, size_t len, int flags);

Please remember, too, that C and C++ are two different languages.

Personally, I think that C is a superb language, and I'm not in the least bit uncomfortable about using "raw pointers" where appropriate.

As it happens, I also think that C++ is a horrible language. I would encourage you to explore C, and I would also encourage you to explore "saner" OO languages like Objective C (primarily in Mac/iPhone Land) or Java (everywhere else) before you lose too much hair worrying about C++ (like taming STL containers). In the aforementioned languages, high-level containers "just work".

IMHO...


All times are GMT -5. The time now is 12:26 PM.