Store values in an array of pointers - c++

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;
}

Related

How to properly insert and display data in an dynamically allocated arrays in C++?

I've been having trouble trying to properly display the correct memory address so I don't know in which memory address I'm inputting data.
#include <iostream>
using namespace std;
int main() {
system("cls");
int *p = new int[2];
for(int i = 0; i < 2; i++) {
cout << "Enter value for address " << p << ": ";
cin >> p[i];
}
for(int i = 0; i < 2; i++) {
cout << *p << " " << p << endl;
p++;
}
}
Here is the output when inputting data:
Here is the output when displaying them:
My concern is it doesn't output the correct memory address when inputting data.
But when displaying them it seems to have no problem displaying the correct memory address.
Your input loop is displaying the p pointer as-is (ie, the base address of the array) on every iteration. It is not adjusting the pointer on each iteration, unlike your output loop which does.
You are also leaking the array, as you are not delete[]'ing it when you are done using it.
Try this instead:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
system("cls");
int *p = new int[2];
for(int i = 0; i < 2; i++) {
cout << "Enter value for address " << &p[i] << ": ";
cin >> p[i];
}
for(int i = 0; i < 2; i++) {
cout << p[i] << " " << &p[i] << endl;
}
delete[] p;
return 0;
}
Alternatively:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
system("cls");
int *p = new int[2];
int *elem = p;
for(int i = 0; i < 2; i++) {
cout << "Enter value for address " << elem << ": ";
cin >> *elem;
++elem;
}
elem = p;
for(int i = 0; i < 2; i++) {
cout << *elem << " " << elem << endl;
++elem;
}
delete[] p;
return 0;
}

Multidimensional array prints hexadecimal numbers instead of the contents of the array. Why?

...C++.....................
#include <iostream>
using namespace std;
int main() {
int troysArray[3][3] = {
{3,2,7},
{4,5,8},
{1,9,2},
};
int i;
int j;
for (i = 0;i < 3;i++)
for (j = 0;j < 3;j++){
cout << troysArray[i] << endl;
cout << troysArray[j] << endl;
};
return 0;
}
.......................
C++
Why does the above code print out hex numbers when I'm actually trying to print out the contents of the array. (Beginner/Just practicing)
What am I doing wrong that's causing this to occur?
The best overload of the std::ostream << operator for troysArray[i] is void* (exploiting pointer decay), and that outputs the address of the pointer.
If you want an element use troysArray[i][j] &c.
troysArray[i] and troysArray[j] are pointers to an array. If you want to print element at i and j, use
cout << troysArray[i][j] << endl;
troysArray is an array of arrays of int.
Thus, troysArray[i] is an array of int, and so is troysArray[j].
There is no overload of operator << for array of int.
However, there is one for void*.
When you pass an array as an argument, what actually gets passed is a pointer to the array's first element.
(In your case, those are &troysArray[i][0] and &troysArray[j][0], both of type int*.)
An int* can be implicitly converted to void*, so the operator << for void* can be used.
This overload outputs the value of the pointer in hexadecimal form.
In order to print the ints you need to print the elements j of each array troysArray[i]:
cout << troysArray[i][j] << endl;
To print it more "matrix-like", with each row on its own line:
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout << troysArray[i][j] << ' ';
}
cout << endl;
}
To print out the contents of the table in a grid (as asked in one of the comments on Guarev Senghai's answer:
#include <iostream>
using namespace std;
int main() {
int troysArray[3][3] = {
{3,2,7},
{4,5,8},
{1,9,2},
};
int i;
int j;
for (i = 0;i < 3;i++)
{
for (j = 0;j < 3;j++)
{
cout << troysArray[i][j];
//uncomment the next line to have a spaces between the numbers.
cout << " ";
}
cout << endl;
}
return 0;
}

i have visual studio error debug assertion failed

In visual studio program crashes: error debug assertion failed. What is wrong in my code? There is no syntax errors. Only warning: deletion of array expression,conversion to pointer suplied When i run it with cmd standart compiler it works fine.
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace std;
#define max_size 100
class my_array{
int* arr[max_size];
public:
my_array() {}
my_array(int size) {
if (size <= 0 || size > max_size) {
exit(1);
}
for (int i = 0; i < size; i++) {
arr[i] = new int;
cout << "Enter element [" << i + 1 << "] = ";
cin >> *arr[i];
}
}
~my_array() {
delete[] arr;
}
void operator[](int n) {
cout << endl;
for (int i = 0; i < n; i++) {
cout << "Enter element [" << i << "] = " << *arr[i] << endl;
}
}
};
int main() {
my_array array(6);
array[5];
return 0;
}
You are deleting arr here:
delete[] arr;
while arr has never been allocated by new. In your original program arr is a fixed size array of pointers to int.
You probably want this:
class my_array {
int *arr;
public:
my_array() {}
my_array(int size) {
if (size <= 0 || size > max_size) { // BTW this test isn't really necessary, as we
// can allocate as much memory as available
// anyway much more than just 100
exit(1);
}
arr = new int[size]; // allocate array of size size
for (int i = 0; i < size; i++) {
cout << "Enter element [" << i + 1 << "] = ";
cin >> arr[i];
}
}
~my_array() {
delete[] arr; // delete array allocated previously
}
void operator[](int n) {
cout << endl;
for (int i = 0; i < n; i++) {
cout << "Enter element [" << i << "] = " << arr[i] << endl;
}
}
};
Instead of having a fixed size array of pointers to int, you have a dynamic array of ints.
There is still room for improvement though. For example the my_array() constructor is pointless here, And it's odd to use the [] operator for printing the content, and the text "Enter element [" in the [] operator is also questionable.

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.