Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way of looping through C++ arrays

Recently I have found a lot of examples, most of them regards the C++ 98, anyways I have created my simple-array and a loop (codepad):

#include <iostream> using namespace std;  int main () {    string texts[] = {"Apple", "Banana", "Orange"};    for( unsigned int a = 0; a < sizeof(texts); a = a + 1 )    {        cout << "value of a: " << texts[a] << endl;    }     return 0; } 

Output:

value of a: Apple value of a: Banana value of a: Orange  Segmentation fault

It's working fine, except the segmentation fault at the end.

My question is, does this array/loop through is done a good way? I am using C++ 11 so would like to be sure it fits the standards and couldnt be done a better way?

like image 732
Lucas Avatar asked Nov 27 '13 05:11

Lucas


People also ask

How do I loop through an array in C?

To iterate over Array using While Loop, start with index=0, and increment the index until the end of array, and during each iteration inside while loop, access the element using index.

How do you use a loop in an array?

For Loop to Traverse Arrays. We can use iteration with a for loop to visit each element of an array. This is called traversing the array. Just start the index at 0 and loop while the index is less than the length of the array.

Can you loop through an array?

You can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run.

Which loop is best used with arrays?

The for loop is probably the most common and well known type of loop in any programming language. For can be used to iterate through the elements of an array: For can also be used to perform a fixed number of iterations: By default the increment is one.


1 Answers

In C/C++ sizeof. always gives the number of bytes in the entire object, and arrays are treated as one object. Note: sizeof a pointer--to the first element of an array or to a single object--gives the size of the pointer, not the object(s) pointed to. Either way, sizeof does not give the number of elements in the array (its length). To get the length, you need to divide by the size of each element. eg.,

for( unsigned int a = 0; a < sizeof(texts)/sizeof(texts[0]); a = a + 1 ) 

As for doing it the C++11 way, the best way to do it is probably

for(const string &text : texts)     cout << "value of text: " << text << endl; 

This lets the compiler figure out how many iterations you need.

as others have pointed out, std::array is preferred in C++11 over raw arrays; however, none of the other answers addressed why sizeof is failing the way it is, so I still think this is the better answer.

like image 178
Nicu Stiurca Avatar answered Sep 24 '22 01:09

Nicu Stiurca