• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 228
  • Last Modified:

Java programmer needs help with C ++

Could someone help me please!? :)
This may be the easiest question every, but how do you get the length of an array in C++? I'm a Java programmer, trying to get the length of an args array passed into 'main'. In Java it would be a case of just coding 'args.length' but C++ didn't like it when i tried this.
Can someone help?
Cheers,
Darren.
0
led_zephrylin
Asked:
led_zephrylin
  • 2
  • 2
1 Solution
 
AlexFMCommented:
Static array:

int array[10];

int n1 = sizeof(array)/sizeof(int);        // number of array elements
int n2 = sizeof(array);                        // length of array in bytes

Dynamic array:

int nSize = 10;
int* pArray = new int[nSize];

int n1 = nSize;                       // number of array elements
int n2 = nSize * sizeof(int);    // length of array in bytes
0
 
SteHCommented:
If you have your main declared as
int main(int argc, char* argv[])
then argc contains the number of arguments available in argv[]. But argv[0] is the program name. So unsual for C/C++ the arguments are found in
argv[1] ... argv[argc].
0
 
rstaveleyCommented:
> how do you get the length of an array in C++?

Ask the person who supplied it :-)

In C++ and C, all you get when you are passed an array as a parameter is the address of its first element. If you declare the array locally, you can use sizeof(), but sizeof() just gives you the size of a pointer, when it is passed as a parameter. The code snippet I posted at http:/Programming/Programming_Languages/C/Q_20797844.html#9757783 illustrates the point.

C++ programmers now benefit from something in the standard library called a vector which is much more like the arrays which you are familiar with in Java... or perhaps Java vectors anyhow :-)  If you use a vector, you have can determin the number of elements from its size().
0
 
rstaveleyCommented:
> argv[1] ... argv[argc].

You mean:

argv[1] ... argv[argc-1]

The argc count includes the executable name. argv[0] has the executable name.
0
 
SteHCommented:
Haven't used the command line for too long. Thx for the correction.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now