LinuxQuestions.org
Help answer threads with 0 replies.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices

Reply
 
Search this Thread
Old 01-27-2011, 03:06 AM   #1
chinho
Member
 
Registered: Dec 2010
Distribution: fedora, openSUSE
Posts: 49

Rep: Reputation: 1
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
 
Old 01-27-2011, 03:45 AM   #2
truboy
Member
 
Registered: Oct 2010
Location: Switzerland
Posts: 84

Rep: Reputation: 9
Quote:
Originally Posted by chinho View Post
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.
 
Old 01-27-2011, 01:24 PM   #3
ForzaItalia2006
Member
 
Registered: Dec 2009
Location: Walldorf, Germany
Distribution: (X)Ubuntu, Arch, Gentoo
Posts: 205

Rep: Reputation: 67
Quote:
Originally Posted by truboy View Post
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
 
Old 01-27-2011, 03:00 PM   #4
paulsm4
Guru
 
Registered: Mar 2004
Distribution: SusE 8.2
Posts: 5,863
Blog Entries: 1

Rep: Reputation: Disabled
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<>".
 
Old 01-27-2011, 03:34 PM   #5
johnsfine
Guru
 
Registered: Dec 2007
Distribution: Centos
Posts: 5,051

Rep: Reputation: 1100Reputation: 1100Reputation: 1100Reputation: 1100Reputation: 1100Reputation: 1100Reputation: 1100Reputation: 1100Reputation: 1100
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.

Last edited by johnsfine; 01-27-2011 at 03:36 PM.
 
Old 01-27-2011, 03:41 PM   #6
z1p
Member
 
Registered: Jan 2011
Location: the right coast of the US
Distribution: Ubuntu 10.04
Posts: 80

Rep: Reputation: 23
Quote:
Originally Posted by johnsfine View Post
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.
 
Old 01-27-2011, 04:03 PM   #7
johnsfine
Guru
 
Registered: Dec 2007
Distribution: Centos
Posts: 5,051

Rep: Reputation: 1100Reputation: 1100Reputation: 1100Reputation: 1100Reputation: 1100Reputation: 1100Reputation: 1100Reputation: 1100Reputation: 1100
Quote:
Originally Posted by z1p View Post
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 View Post
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.

Last edited by johnsfine; 01-27-2011 at 04:07 PM.
 
Old 01-28-2011, 01:30 AM   #8
paulsm4
Guru
 
Registered: Mar 2004
Distribution: SusE 8.2
Posts: 5,863
Blog Entries: 1

Rep: Reputation: Disabled
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...
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
How do I get number of elements in a hash of arrays? RavenLX Programming 2 12-10-2008 12:44 PM
how do i write a asci-char withthe number? kalleanka Programming 11 04-28-2008 12:53 PM
awk: Using split to divide string to array. How do I find out the number of elements? vxc69 Programming 9 02-09-2008 12:49 PM
perl - get number of elements in an array AM1SHFURN1TURE Programming 3 03-07-2005 03:59 PM
How do I add character+number to get char in C++? needforspeed Programming 10 02-10-2004 12:16 AM


All times are GMT -5. The time now is 05:04 AM.

Main Menu
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration