Sunday, July 12, 2009

How to find the end of an array in C++?

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?

How to find the end of an array in C++?
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 %26lt;iostream%26gt;


using namespace std;





int main()


{


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


cout%26lt;%26lt;sizeof array%26lt;%26lt;endl;


char array2[10] = {'a' , '2' , 'r' , 't' , 'y' , 'u' , 'y' , 'n' , '1' , '8'};


cout%26lt;%26lt;sizeof array2%26lt;%26lt;endl;


return 0;


}


// End here.


// Good luck
Reply: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].
Reply: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
Reply: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 :)


No comments:

Post a Comment