Advertisement

Array Length

Started by April 05, 2002 06:48 PM
14 comments, last by Xanth 22 years, 7 months ago
Is there a way to get the length of any Array? I figured out how to do it for arrays of type "char" (Strings) but I''m finding it harder for other types.
"I thought Genius lived in bottles..." - Patrick Star
If it is a statically sized array, such as
int foo[100];

you can use
sizeof(foo)/sizeof(int)

To calculate the number of elements in the array.
Advertisement
It''s not static.

I''m not sure if I''ll actually need it but it''s still something I''d like to know.
"I thought Genius lived in bottles..." - Patrick Star
If you have just a pointer to the first element of the array, there is no way of knowing the array''s length.
---visit #directxdev on afternet <- not just for directx, despite the name
quote: Original post by jaxson
If it is a statically sized array, such as
int foo[100];

you can use
sizeof(foo)/sizeof(int)

To calculate the number of elements in the array.


alternatively:

sizeof(foo)/sizeof(foo[0])
"I thought what I'd do was, I'd pretend I was one of those deaf-mutes." - the Laughing Man
In C#, arrays are also object. All arrrays are derived from System.Array (if I''m not mistaken), which contains the Length property. So in C# to get the length of the array you can do like this:

using System;public class ArrayLengthDemo{ public static void Main() {  int x = int.Parse(Console.ReadLine());  int[] intArray = new int[x];  Console.WriteLine("Length is" + intArray.Length); }} 


in C or C++ (also doable in C#), like the other guy said, is by dividing the total size of the array by the element size, eg:

int length = sizeof(intArray) / sizeof(intArray[0]);

Visit A Whole New World : World of 3d Art!
http://3d-gallery.cjb.net
Visit A Whole New World : World of 3d Art!http://3d-gallery.cjb.net
Advertisement
C# looks alot like Java, I should probably look into it some more.

Thanks for all the replies everyone. I appreciate the help.
"I thought Genius lived in bottles..." - Patrick Star
That''s why we advocate std::vector.

[ GDNet Start Here | GDNet Search Tool | GDNet FAQ | MS RTFM [MSDN] | SGI STL Docs | Google! | Asking Smart Questions ]
Thanks to Kylotan for the idea!
No, you really shouldn''t look into c#.
What good is a proprietary programming
language? How stable is a language whose
"standard" is defined by a single corporate
entity?

C# == VB++
GameDev Reader TODO List:1. Name my company.2. Buy domain name.3. Create web site.4. Name myself as CEO5. Create Game Engine.6. Design game.
It''s Microsoft?

Well they''re gonna rule over everything anyway.
"I thought Genius lived in bottles..." - Patrick Star

This topic is closed to new replies.

Advertisement