English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Hi All,

I'm currently trying to learn C++ and I've been looking for a clear answer to this question. I understand to find the end of an array it is the length of the array minus 1. I'm little confused on the syntax. Could one of you point me in the right direction?

2007-02-11 04:05:09 · 4 answers · asked by beleoa 1 in Computers & Internet Programming & Design

4 answers

An array always starts with index 0. That is, if you initialize an array like:

int array [10] = {2,4,1,2,8,9,0,1,5,6};

array[0] = 2
array[1] = 4
array[8] = 5
array[9] = 6

No one on the planet could know what array[10] is! because it is a memory cell that holds a totally random value.

Now if you want to know the array's size or length, use "sizeof()" method. If the array is of type integer "int" it will give you 4 for every element. In our example, we will get 40 bytes because we have 10 elements each having 4 bytes long. so, the length is equal to 40/4 = 10. If the array is of type "char", we would get 10 because the size of each element is 1 byte here.

------------------
Example:
You can copy the following simple program and paste it into any C++ compiler and it will work:

// Start here
#include
using namespace std;

int main()
{
int array[10] = {1,4,5,3,2,4,5,6,9,8};
cout< char array2[10] = {'a' , '2' , 'r' , 't' , 'y' , 'u' , 'y' , 'n' , '1' , '8'};
cout< return 0;
}
// End here.
// Good luck

2007-02-11 08:14:41 · answer #1 · answered by SPECTACULAR 3 · 0 1

I believe you're looking for the last index in an array, without knowing the length or type of array element. Well this is all handled with the sizeof operator and are given in bytes (as with most things in C++).

For Example:
Element_size = sizeof myarray[0]; // size of each element in bytes
Array_size = sizeof myarray; // total size in bytes

Last_array_index = Array_size / Element_size - 1

Hope this is what you're after :)

2007-02-11 04:24:44 · answer #2 · answered by Grand Turizmo 1 · 2 0

Make an array A with i number of elements.
If you want the last element of the array A[i] to be x, then:

x = A[i-1];

And the first element would be A[0].

2007-02-11 04:15:49 · answer #3 · answered by Anonymous · 1 2

you can use "sizeof()", which will give you the size of the array as it was defined. OR you can use "strlen()" to get how much of the array is being used.
Example:

char myarray[10];
char somearray[] = "test";
int length;

strcpy(myarray, somearray); //copy "test" to myarray
length = sizeof(myarray); //get length using sizeof
//length = 10
length = strlen(myarray);//get length using strlen
//length = 4

2007-02-12 01:15:58 · answer #4 · answered by justme 7 · 0 0

fedest.com, questions and answers