Help with dynamic arrays

Just trying to fill a dynamically allocated array with values then I want to print out the values using pointer method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
using namespace std;

long * extend_arr(long int arr[], long int length, long int val)
{
  long * array2 = new long [length + 1];
  for (int J = 0; J < length; ++J)
    array2[J] = arr[J];
  
  array2[length] = val;
  
  delete[] arr;
  arr = NULL;
  
  return array2;
}

void FillMyArrayWithPrimes(long arr[], int length )
{
  for (int P = 3; P < 100; P += 2)
    if (isPrime(arr, P))
    {
      arr = extend_arr(arr, length, P);
      ++length;
    }
    for (;*arr > 0; ++arr)
      cout << *arr << " ";
}

int main()
{
  long *Block = new long [1];
  *Block = 2;
  FillMyArrayWithPrimes(Block, 1);
  
  return 0;
}


When this runs, I get an array with random numbers in it. For example, just trying to print the first value in *Block gives me random numbers each time. Can anyone tell me what is wrong with this as to why it is not holding the right values?

The extend_arr works perfectly fine, because when I try to access the values in the array using indexes (arr[0], arr[1], etc) it shows the right output, but using pointers does not. How can I make it work?

Output:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 134561 23 29 640 112


As you can see, the primes end at 97 but it just keeps printing more


EDIT:
It now prints the correct values in the function if I set the last value in the array to 0. arr[length] = 0;

Now if I wanted to print the values in the array within main, why is that not working?

EDIT2:
Nvm, I just changed the void function to return a pointer to an array and problem solved!
Last edited on
C-style arrays doesn't store information about their length. What happens is you getting your pointer in for (;*arr > 0; ++arr) point to area of memory outside an array, where some random data is stored. You should manually check if your pointer is in array, like that: for (;arr < (arr + length); ++arr)
Figured that was the problem, thanks anyway for the reply
Topic archived. No new replies allowed.