-4

I have been getting a weird output if I initialize an array using a variable instead of a constant the two code below produces a different output for me.

int x =7;
int arr[x];

and

int arr[7];

the first one generates this output

78  9  73  32  6422216  50  42

and the 2nd one

78  9  73  54  29  50  42

I need to use the size of an vector for the array size. I have tried making the variable constant but it doesn't makes a difference.

edit using the array here

int arr[size];
for(int j=i;j<nums.size();j++)
    arr[j+1]=nums[j];
arr[i]=nums[signs.size()];
for(int j=0;j<nums.size();j++)
    nums[j]=arr[j];
Cœur
  • 37,241
  • 25
  • 195
  • 267
irrelevent
  • 27
  • 1
  • 6

1 Answers1

1

In neither of your two cases is the array initialized.

Without an explicit initializer, the contents of an array (or any variable) are indeterminate. You can't predict what those values will be. And if one of those values happens to be a trap representation, you invoke undefined behavior if you attempt to read that value.

If you want your array to have a particular set of values to start, you need to set those values explicitly, either with an initializer or by assignment.

dbush
  • 205,898
  • 23
  • 218
  • 273