Issue with Array assignment - c++

I am having an issue with outputting an array. When I output each element without a for loop, the program runs fine. When I try to output with a for loop, the program crashes the first time I set an element in the array. I have marked the line where the program crashes when I uncomment out the for loop. My sort seems to work fine and the program is crashing way before that, so I'm pretty sure that isn't the issue. Any ideas why the 2nd for loop would crash the program at the specified line?
int main()
{
int* Array;
int j = 5;
for(int i=0; i<5; i++)
{
Array[i] = j; //Crashes here with 2nd for loop uncommented
cout << Array[i] << endl;
j--;
}
Array = insertion_sort(Array);
cout << Array[0] << endl;
cout << Array[1] << endl;
cout << Array[2] << endl;
cout << Array[3] << endl;
cout << Array[4] << endl;
/*for(int k=0; k <5; k++)
{
cout << Array[k] << endl;
}*/
}

You are accessing the pointer before initializing it. You should change
int* Array;
to
int* Array = new int[5]; // There are 5 ints in my array
and make sure to
delete[] Array;
at the end, or even better:
int Array[5]; // This way you don't need the new keyword, so you won't need to delete[] later

Right now, your array is not instanciated. It's just a pointer. You need to choose how large of an array you want before you can start writing to it.
int* Array = new int[5];
int j = 5;
for(int i=0; i<5; i++)
{
Array[i] = j; //Crashes here with 2nd for loop uncommented
cout << Array[i] << endl;
j--;
}

Related

Store values in an array of pointers

I want to store values in an array of pointers. I have done the below so far but it doesn't work as I expected:
#include <fstream> //for file IO (ifstream)
#include <iostream> //for cin >> and cout <<
using namespace std;
#define MAX_N 1000
int *ptr[MAX_N]; //It declares ptr as an array of MAX integer pointers
int myptr = 0;
int main() {
for (int i = 0; i < 3; i++)
{
myptr++;
}
ptr[0] = &myptr; // assign the address of integer
cout << *ptr[0] << endl;
for (int i = 0; i < 2; i++)
{
myptr++;
}
ptr[1] = &myptr; // assign the address of integer
cout << *ptr[1] << endl;
for (int i = 0; i <= 1; i++) {
cout << "Value of element " << i << ": " << *ptr[i] << endl;
}
return 0;
}
I want the the last loop outputs:
Value of element 0: 3
Value of element 1: 5
But it gives me:
Value of element 0: 5
Value of element 1: 5
Apparently, I am missing something. Both elements point to the same address which I cannot understand because the variable myptr changes its values.
Can anyone help me with this?
Thanks
You just make both pointers point to the same memory address. You never allocate additional memory for more ints which is why you always read the value currently stored in myptr. To allocate additional memory use new and don't forget to free all the newly allocated memory at the end:
#define MAX_N 1000
// make sure the pointers are initialized as null pointers
int* ptr[MAX_N] { nullptr }; //It declares ptr as an array of MAX integer pointers
int myptr = 0;
int main() {
for (int i = 0; i < 3; i++)
{
myptr++;
}
ptr[0] = new int(myptr); // dynamically create an int with the value currently stored in myptr
cout << *ptr[0] << endl;
for (int i = 0; i < 2; i++)
{
myptr++;
}
ptr[1] = new int(myptr); // allocate another int
cout << *ptr[1] << endl;
for (int i = 0; i <= 1; i++) {
cout << "Value of element " << i << ": " << *ptr[i] << endl;
}
// free all the allocated ints (delete null doesn't hurt)
for (int* p : ptr)
{
delete p;
}
return 0;
}

How to find out addresses of the slots in dynamically allocated multidimensional array?

I created a 2-dimensional dynamically allocated array. Then I wanted to output the addresses of the slots, so I can really see it's not a contiguous block of memory. I've managed to do that by &tda[i][j] statement. However, I'm wondering how I could do that by using something like *(tda+1), which is the same as &tda[1][0]. For example, how could I output tda[1][1] address using a combination of *(tda+1).
#include <iostream>
using namespace std;
int main() {
int **tda;
tda = new int*[2];
cout << tda << endl;
cout << tda+1 << endl;
for (int i=0; i<2; i++) {
tda[i] = new int[2];
}
cout << *(tda+1) << endl;
cout << endl << "Proof that the block of memory is not contiguous:" << endl;
for (int i=0; i<2; i++) {
for (int j=0; j<2; j++) {
cout << &tda[i][j] << endl;
}
}
return 0;
}
Well, you already mentioned the equivalence of a[k] and *(a + k), but let me spell it out for you:
&tda[i][j]
is
&*(tda[i] + j)
is
*(tda + i) + j
Analogously,
tda[i][j]
becomes
*(*(tda + i) + j)

Run Time Check Failure #2, AND array values swapped with outputs incorrectly

I've been struggling with this piece for a while now. I've googled run time check failure and I have no idea what to do. From what I get, it's because I declared swapEven and swapOdd to have an array of size 0? I initially had this set up as a pointer array, but that just didn't work. Can anybody point me in the right direction please? Thanks in advance!
void arrangeArrayJesseRagsdale(int* ary1, int* ary2, int arraySize1, int arraySize2) {
int i, j;
int temp;
int swap = 0;
int* swapEven = 0;
int* swapOdd = 0;
swapEven = new int[arraySize1];
swapOdd = new int[arraySize2];
cout << " Original Arrays\n Array #1: ";
for (i = 0; i < arraySize1; i++) {
cout << ary1[i] << " ";
}
cout << endl << " Array #2: ";
for (i = 0; i < arraySize2; i++) {
cout << ary2[i] << " ";
}
cout << endl;
for (i = 0; i < arraySize1; i++) {
for (j = 0; j < arraySize2; j++) {
if (ary1[i] % 2 != 0) {
if (ary2[j] % 2 == 0) {
temp = swapOdd[i] = ary1[i];
ary1[i] = swapEven[i] = ary2[j];
ary2[j] = temp;
swap++;
}
}
}
}
cout << "\n Updated Arrays\n Array #1: ";
for (i = 0; i < arraySize1; i++) {
cout << ary1[i] << " ";
}
cout << endl << " Array #2: ";
for (i = 0; i < arraySize2; i++) {
cout << ary2[i] << " ";
}
cout << endl;
if (swap > 0) {
cout << "\n Swapping info -\n";
for (i = 0; i < swap; i++) {
cout << " Array #1 value " << swapOdd[i] << " swapped with Array #2 value " << swapEven[i] << endl;
}
}
cout << "\nThere is/are " << swap << " swap(s)." << endl << endl;
delete[] swapEven;
delete[] swapOdd;
return;
}
First, your arrays here:
int swapEven[] = {0};
int swapOdd[] = {0};
Have 1 element each.
Second, your loops use arraySize1 and arrraySize2 to index into the arrays above. There is no check whatsoever in your code to ensure that the indexing into these arrays are within bounds. More than likely, this is where your error occurs, and that is accessing the array out-of-bounds.
If your goal is to create arrays with the same number of elements, use std::vector:
#include <vector>
//...
std::vector<int> swapEven(arraySize1, 0);
std::vector<int> swapOdd(arraySize2, 0);
The rest of the code stays the same.
swapEven and swapOdd do not have zero size, they are arrays containing the single integer element, 0. These arrays therefore have length 1.
However, from what I can tell from your code, you need to declare swapOdd to have at least as many elements as does ary1. Similarly, swapEven needs to have at least as many elements as does ary2. This is because you are storing values in those arrays using the indices of ary1 and ary2. Writing to unallocated memory may cause the crash that you see.
Also use of the indices of the 2 arrays will result in non-contiguous storage of the swapped values in swapOdd and swapEven. The affect of this is that the swap reporting code will use the wrong array elements when generating the report.
You might be better off using a dynamic "list" data structure for accumulating the swapped elements. C++ has a few alternatives there such as list and vector and these could be used instead of the swap arrays.
One other thing, rather than use pointer arithmetic to access the elements of arrays ary1 and ary2, it's more readable to use array indexing, i.e.
ary[i]
instead of
*(ary1 + i)

Confusing error when deleting dynamically allocated array in C++

I am trying to implement a simple merge sort algorithm. What I am very confusing is that
I keep getting the following error message right after the "array2" is deleted.
"
free(): invalid next size (fast)
"
Please advise. Thank you very much!
#include <iostream>
#include <limits.h>
using namespace std;
void merge_sort(int*,int,int);
int main(){
//cout << "Max int: " << INT_MAX <<endl;
int n;
cin >> n;
int* array = new int(n+1);
for (int i=1; i<=n; i++)
cin >> array[i];
merge_sort(array,1,n);
cout << "--------------------------------------------" <<endl;
for (int i=1; i<=n; i++)
cout << array[i] <<endl;
}
void merge_sort(int* array,int p,int r){
cout << p << ' ' << r <<endl;
if (p == r)
return;
int q = int((p+r)/2);
merge_sort(array,p,q);
merge_sort(array,q+1,r);
//(p..q) and (q+1 .. r) sorted, then merge this two sorted array
int n1 = q-p+1;
int n2 = r-q;
cout << "Mark1 " <<n1<<' '<<n2<<endl;
int *array1;
array1 = new int(n1+1);
int *array2;
array2 = new int(n2+1);
for (int i=p; i<=q; i++)
array1[i-p] = array[i];
for (int i=q+1; i<=r; i++)
array2[i-q-1] = array[i];
array1[n1] = INT_MAX;
array2[n2] = INT_MAX; //CONSTANT, serve as sentinel
int p1 = 0;
int p2 = 0;
cout << "Mark2" << endl;
for (int i=p; i<=r; i++){
if (array1[p1]<array2[p2]){
array[i] = array1[p1];
p1++;
}else{
array[i] = array2[p2];
p2++;`enter code here`
}
}
cout << "Mark3" << endl;
delete [] array2;
cout << "Delete array2 " << endl;
delete [] array1;
cout << "Delete array1 " << endl;
}
The syntax
new int(n+1)
Creates a single int on the free-store and initialises it with n+1, and right away you access it out of bounds with array[1]. You want brackets:
new int[n + 1]
Which will create an array. The same goes for every other place like that in the program.
Also, since you are starting your loop at 1, the object array[0] is uninitialised and you get undefined behaviour if you access it, which you do. This is wasting an array element for nothing and setting up traps for yourself, I recommend you don't add 1 to the array size and start your indices from 0.

Array Pointer in C++

int n;
int *array[8]
cout<<"Enter Number Between 0-9 Only"<<endl;
for(int i = 0; i< 9; i++){
cout << "Enter Number " << (i + 1) << endl;
cin >> n;
if((n >= 0) && (n <= 9))
array[i] = &n;
else {
cout << "Numbers from 0-9 only\n" << endl;
i--;
}
}
cout << *array[0] << endl;
}
I'm trying to store 9 entered numbers in a pointer array but its not working why?? Can you explain why to me and how to solve it or improve it. I'm just a beginner and its not homework im testing what i had read.
The line
array[i] = &n;
will store the same address in every entry in your array. This is just pointing to n so will always point to that value.
Either define the array as an array of integers
i.e. int array[9];
and then place the value into that array
i.e. array[i] = n;
OR
Allocate some memory off the heap
i.e.
int *array[9];
...
array[i] = new int;
*array[i] = n;
But you will then have to free this memory with delete to avoid a memory leak.
There are several issues here.
You have nowhere to store the values. You have an array of 8 pointers which are all set to point to the same variable n, which is on the stack and so goes out of scope.
The array has 8 elements so the loop goes one past the end
This is C++ so really best not to use C arrays unless you have a justifiable reason to.
I would have something more like *NB not compiled and run)
{
...
std::vector<int> array;
cout<<"Enter Number Between 0-9 Only"<<endl;
for(int i = 0; i< 8; i++){
int n;
cout << "Enter Number " << (i + 1) << endl;
cin >> n;
if((n >= 0) && (n <= 9))
array.push_back(n);
else {
cout << "Numbers from 0-9 only\n" << endl;
i--;
}
}
cout << array[0] << endl;
}
You are saving a pointer to n in the array, but you constantly change the value of n.
You don't really need to mess with pointers here. Change your array definition, how you populate it, and how you display and you should have better luck.
int array[9];
...
array[i] = n;
...
cout << array[0] << endl;