1,105,644 Community Members

Array Length

Member Avatar
Slate2006
Newbie Poster
18 posts since Oct 2007
Reputation Points: 0 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]
 
0
 

Is there a function used to calculate the length of an array. For instance, if someone enters John, the function outputs 4. Or is it necessary to write a function to do it, and how is it done. (This is not homework this time, just want to know for my job).

Member Avatar
vmanes
Postaholic
2,140 posts since Aug 2007
Reputation Points: 1,165 [?]
Q&As Helped to Solve: 282 [?]
Skill Endorsements: 10 [?]
 
0
 

You are asking two different questions.

To find the length of an array (the amount of storage allocated to it), you can use the sizeof( ) operator, but only in the function where the array was allocated. As in:

int arr[] = { 1, 2, 3, 4, 5, 6 };
   int size = sizeof( arr ) / sizeof( arr[0] );
   cout << size << endl;

Your second question seems to be asking how to find the length of text entered into a string. There, an array of some size will have been allocated, but you will only be using the portion of it that has valid text in it. Assuming you're using locally declared char array, you might find the length of text (the string size) thusly:

char text[100] = "";
   strcpy( text, "John" );
   int len = (int) strlen( text );
   cout << len << endl;

Val

Member Avatar
Narue
Bad Cop
12,139 posts since Sep 2004
Reputation Points: 5,693 [?]
Q&As Helped to Solve: 1,537 [?]
Skill Endorsements: 81 [?]
Team Colleague
 
1
 

If it's actually an array, there are two common ways to find the size. The first is a template that converts an array of type T to an array of type char, which can then be used as the operand to sizeof to get the number of elements:

#include <iostream>

template <typename T, size_t N>
char (&array(T(&)[N]))[N];

int main()
{
  int a[10];

  std::cout<< sizeof array ( a ) <<'\n';
}

The other is a macro that divides the size of the array by the size of a single element to give you the number of elements:

#include <iostream>

#define length(a) ( sizeof ( a ) / sizeof ( *a ) )

int main()
{
  int a[10];

  std::cout<< length ( a ) <<'\n';
}

The template is type safe, and won't let you accidentally take the size of a pointer. The object must be an array. The macro will let you pass a pointer, but because a pointer isn't an array, the result will be wrong. Therefore, you should prefer the template method.

If it's not actually an array, but a pointer to the first element, you're basically screwed unless there's a sentinel value at the end of the array (like the '\0') in C-style strings, or you have the size stored elsewhere.

>For instance, if someone enters John, the function outputs 4.
If this is a C-style string, use std::strlen to get the length of the string, or use a loop to find the '\0':

int n = 0;

while ( a[n] != '\0' )
  ++n;

// n has the length of the string now

If it's a C++ string, which you should be using in your job, you can use the length or size member functions to get the number of characters.

Member Avatar
Slate2006
Newbie Poster
18 posts since Oct 2007
Reputation Points: 0 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]
 
0
 

My program works fine now...until you enter a space..

#include <iostream>
#include <string.h>
using namespace std;

int arraylength(char my[]);

int main(){

	char my[100];
	int size;

	cout << "Please enter your name: ";
	cin >> my;

	size=arraylength(my);
	cout << size << endl;

	return 0;
}

int arraylength(char my[]){
	char i=my[0];
	int j=0;
	while (my[j] != '\0'){
		j++;
	}
	return j;

}

When you enter a space it output the length of the array before the space.

Member Avatar
vmanes
Postaholic
2,140 posts since Aug 2007
Reputation Points: 1,165 [?]
Q&As Helped to Solve: 282 [?]
Skill Endorsements: 10 [?]
 
0
 

That's because cin >> my; skips preceding whitespace, grabs characters until it again encounters whitespace (blank, tab, newline.)
Use getline, as in:

cin.getline( my, 100 );

This reads all input (including blanks and tabs) for up to size-1 characters or until newline (the default delimeter, you can specify some other delimiter character as a third parameter.)

Val

Member Avatar
Slate2006
Newbie Poster
18 posts since Oct 2007
Reputation Points: 0 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]
 
0
 

Thanks this has helped a bunch. I am finally starting to understand all or this.

Member Avatar
vijayan121
Posting Virtuoso
1,769 posts since Dec 2006
Reputation Points: 1,097 [?]
Q&As Helped to Solve: 329 [?]
Skill Endorsements: 16 [?]
 
0
 

> a template that converts an array of type T to an array of type char, which can then be used as the operand to sizeof to get the number of elements:

template <typename T, size_t N>
char (&array(T(&)[N]))[N];

another way to use the same template idea (which i find slightly more readable) is:

#include <cstddef>
#include <iostream>

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

int main()
{
   int a[] = { 0, 1, 2, 3, 4, 5, 6 };  
   const void* b[] = { a, a+1, a+2, a+3 };
   std::cout << size(a) << '\t' << size(b) << '\n' ;
}
Member Avatar
Narue
Bad Cop
12,139 posts since Sep 2004
Reputation Points: 5,693 [?]
Q&As Helped to Solve: 1,537 [?]
Skill Endorsements: 81 [?]
Team Colleague
 
0
 

>which i find slightly more readable
If it were readable, it wouldn't be a proper template definition. :D

Member Avatar
Calicoder
Newbie Poster
1 post since Dec 2011
Reputation Points: -4 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
-1
 
template <typename T, size_t N> 
size_t getSize(T(&)[N]) {
    return N;
}

int main () {
int justAnArray[10];
std::cout << "size of array: " << getSize(justAnArray);
return 0;
}
Member Avatar
adityatandon
Junior Poster
114 posts since Dec 2011
Reputation Points: 23 [?]
Q&As Helped to Solve: 13 [?]
Skill Endorsements: 0 [?]
 
0
 

For accepting a String :
Cin works for accepting strings till a space is discovered.
Instead of using cin.getline you can also use the gets() [available under string.h] function which accepts a string. It stands for 'get string'!!

To Find Length of String :
Two ways :
1) Use strlen() - stands for string length (Found under string.h)
2) Run a for or a while loop checking every element encountering '\0' as all strings are terminated by that. Also make sure to keep incrementing a variable by 1, so when u find '\0' you can break from the loop and the variable who were incrementing has the length of the string !

Member Avatar
zeroliken
Nearly a Posting Virtuoso
1,222 posts since Nov 2011
Reputation Points: 79 [?]
Q&As Helped to Solve: 216 [?]
Skill Endorsements: 15 [?]
 
0
 

For accepting a String :
Cin works for accepting strings till a space is discovered.
Instead of using cin.getline you can also use the gets() [available under string.h] function which accepts a string. It stands for 'get string'!!

To Find Length of String :
Two ways :
1) Use strlen() - stands for string length (Found under string.h)
2) Run a for or a while loop checking every element encountering '\0' as all strings are terminated by that. Also make sure to keep incrementing a variable by 1, so when u find '\0' you can break from the loop and the variable who were incrementing has the length of the string !

If you look at the date of post,this thread was created in 2007
Let it rest in peace

Member Avatar
Sebelius
Newbie Poster
1 post since Sep 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

In the editor options menu you can set c++ to add a null detemined value at the end of each string; '\0'. Then it's pretty easy to detemine the lenght of any string. However, when it comes to string type arrays, i just declare a constant value which i set to be the last element of any string array that i declare. This way you will always know, let's say through a for loop the total elements of that array, and you will also know that the valued or elements of importance is always total - 1. When it comes to int arrays however, i am unsure.

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article