-3

so i have this code in C++ where i have an array of an undefined initial value, and the user is supposed to keep entering values for the array until exit code -1. once that is entered the array size is determined by the number of inputs. then it has to be split in half into two arrays the first having the first half of the original array and the second having the second half of the original array.

#include <iostream>
using namespace std;

int main()
{
    int n;
    n++;
    int a[n];
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
        n++;
        if (a[i] == -1)
        {
            n--;
            break;
        }
    }
    cout << n << endl;
    int e[n / 2];
    for (int j = 0; j < (n / 2); j++)
    {
        e[j] = a[j];
    }
    int q = 0;
    int o[n / 2];
    for (int l = (n / 2); l < n; l++)
    {
        o[q] = a[l];
        q++;
    }
    for (int h = 0; h < n / 2; h++)
    {
        cout << e[h] << "  ";
    }
    cout << '\n';

    for (int h = 0; h < n / 2; h++)
    {
        cout << o[h] << "  ";
    }
    return 0;
}

the problem i'm facing is that ,when the array if sized 4, it works fine, but when it's sized 6 , the 5th and 6th value become 3 0 . instead of the value i entered . and making a larger array has a similar problem certain values in the array are damaged.

mch
  • 9,424
  • 2
  • 28
  • 42
  • 3
    `int a[n];` is not standard c++, use `std::vector` instead. [Why aren't variable-length arrays part of the C++ standard?](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) – 463035818_is_not_an_ai May 12 '21 at 09:19
  • @largest_prime_is_463035818, does that mean that the OP is compiling with some option to get it work anyway? – Enlico May 12 '21 at 09:31
  • 2
    @Enlico gcc needs some pushing via `-pedantic` to disable extensions. I mean using extensions is fine, as long as one is aware that it is an extension and code is non-portable. Though, it is often missed and misunderstood that here VLAs are neither needed nor are they the right tool (some "tutorials" promote them, I have no clue why) – 463035818_is_not_an_ai May 12 '21 at 09:34
  • Thanks! I'm so happy such a thing didn't get in my sight long ago :D – Enlico May 12 '21 at 09:36

2 Answers2

2
int n;
n++;

You're incrementing a variable that has an indeterminate value. The behaviour of the program is undefined. How big is the array supposed to be?

int a[n];

The size of your array variable isn't compile time constant. The program is ill-formed. Either use a compile time constant size, or allocate the array dynamically. Simplest way to achieve the latter is to use std::vector.

then it has to be split in half into two arrays

I suspect that there may be a XY-problem here. Would it be sufficient to have iterators to the different halves of the original array? This way there is no need to create additional arrays, nor to copy values into those arrays.

Here is one such solution:

auto first  = std::begin(a);
auto middle = std::next(first, n/2);
auto last   = std::end(a);
std::span first_half  {first,  middle};
std::span second_half {middle, last  };
eerorika
  • 232,697
  • 12
  • 197
  • 326
-1

Your code splits the array just fine. It only has errors when taking the array elements from input and in printing the arrays.

As largest-prime-is-463035818 said, std::vector is a better data structure to use. However, if you are only allowed to use arrays, assume a maximum size for your array size since arrays need a size when declared.

#include <iostream>
#define MAX 1000
using namespace std;
int main()
{
    int n;
    n++;
    int a[MAX];
    for (int i = 0; i < MAX; i++)

Initialize n to 0. This is to avoid getting n with garbage values. Remove n++; as you shouldn't be incrementing it at the start.

int main()
{
    int n = 0;
    int a[MAX];
    for (int i = 0; i < MAX; i++)

To print the other array correctly, use n - n / 2 instead to compute for the correct size of the other array.

int o[n - n / 2];
for (int l = (n / 2); l < n; l++)
{
    o[q] = a[l];
    q++;
...
for (int h = 0; h < n - n / 2; h++)
{
    cout << o[h] << "  ";
}

Note: You could omit the braces in the for loops when the block has only one statement. Also, use more meaningful identifiers to make it more readable (What is q? What does the array o represent?)

AcidResin
  • 134
  • 2
  • 12
  • Explain why it was voted `-1` or give suggestions to improve my answer – AcidResin May 12 '21 at 11:14
  • assuming `MAX` size when the size is determind by user input is bad advice. Using macros for constants is bad advice. Omitting braces on `for` is bad advice. Not mentioning undefined beahvior in OPs code is missing imporant aspect, while mentioning "garbage" is supporting not useful myth about UB. – 463035818_is_not_an_ai May 12 '21 at 11:40
  • How is `size` determined in the input? The user puts arbitrary number of elements, it can't be known before the program starts. How is the use of macros bad? It makes the code more readable. Omitting braces? The for loop has only one statement to execute. What myth do you mean? – AcidResin May 12 '21 at 13:55
  • It cannot be known before the program starts, thats the point. The array can have dynamic size also without `std::vector`. Macros are the wrong tool for the job, they have downsides that arent needed here. `const size_t size = 1000;` is not less readable. I was refering to the "garbage" myth. The code needs a fix not because it might produce garbage output, but because it is broken even when it could produce ok looking output. Btw I am not "explaining a vote", voters don't have to nor should they explain their votes (I'll search the relevant metapost). Just making suggestions for improvment – 463035818_is_not_an_ai May 12 '21 at 14:05
  • fyi https://meta.stackoverflow.com/questions/285081/am-i-still-supposed-to-explain-my-downvotes-or-not – 463035818_is_not_an_ai May 12 '21 at 14:06
  • This is the first time I've heard of a "downside of macros". Could you further explain that? And what do you mean by "it is broken even when it could produce ok looking output."? – AcidResin May 12 '21 at 14:13
  • I dont like the title, but here some stuff about "Evil Macros" https://stackoverflow.com/questions/14041453/why-are-preprocessor-macros-evil-and-what-are-the-alternatives and "can produce ok looking output" is just the nature of [undefined behavior](https://en.cppreference.com/w/cpp/language/ub). In OPs code `n++;` invokes ub, but nevertheless the code might seem to work as expected, and it is such occurences of ub that one has to fear most. OP writes "...if sized 4, it works fine," but actually the code is not "fine" for any size – 463035818_is_not_an_ai May 12 '21 at 14:19
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/232293/discussion-between-acidresin-and-largest-prime-is-463035818). – AcidResin May 12 '21 at 14:24