开发者

print out array of arbitrary length

开发者 https://www.devze.com 2023-01-11 06:15 出处:网络
I am trying to print print out an array of integers whose length I don\'t know in开发者_如何学运维 C++. Here is my attempt.

I am trying to print print out an array of integers whose length I don't know in开发者_如何学运维 C++. Here is my attempt.

    int i = 0;
    while ( X != NULL){
            cout << *(X+i) << " ";
            i+=1;
    }

X is the array. My problem is to stop upon printing last element.


Either the last element in your array will have to be some magic value (0 or -1 or INT_MAX or something similar) that you can watch for and thus use it to stop looping. Or else you must find a way to record the length of the array.

There is no standard way in C++ to determine the length of an arbitrary array.

The other alternative is to stop using raw arrays and use a smarter object such as std::vector which gives you array-like access but also keeps track of the number of elements stored in it.


int i = 0; 
while ( *(X+i) != NULL){ 
        cout << *(X+i) << " "; 
        i+=1; 
} 

Assuming your array is null-terminated.
However it would be much much better if you kept track of the length of your array, or even better use a vector.


You could find out the size of the array if X is an array and not a pointer:

int X[unknownsize];

size_t arraysize = sizeof(X)/sizeof(int);

for(int i=0;i<arraysize;i++)
{
  cout << X[i] << " ";
}


The loop you've written never modifies X, so assuming it's a valid array the loop will loop forever (or until it crashes by running some amount off the end).

The C++ way to solve this is to not use arrays but to use std::vector instead. It keeps track of all the bookkeeping including length for you automatically.

If X is an actual array (like int X[5];) you can use (sizeof(X) / sizeof(X[0])) to get the number of elements in the array. If X is passed as a pointer then there is no way in C or C++ to get the length. You must pass the length along with the array in that case.

You could play games with "magic" numbers in the array that mean end (for example if it must always be positive you could use -1 to signal the end, but that's just asking for obscure bugs. Use std::vector.


First you need to find the size of the array and iterate until the size of the array to output the array elements as below,

size_t size = sizeof(X)/sizeof(X[0]);

for (size_t i=0; i<size; i++)
{
    cout << X[i] << " ";
}


If you declared the array there's an old C trick to get it's size:

int  array[10];

for ( int i = 0; i < sizeof(array) / sizeof(array[0]); i++ )
  printf( "%d", array[i] );


You have a few options:

  1. Use vector which keeps track of the number of elements in your array.
  2. Have a length variable and manually keep track of size.
  3. Mark the last element of your array with a null pointer i.e. '\n'

(2)

0

精彩评论

暂无评论...
验证码 换一张
取 消