C++ Array of Pointers not assignable - c++

I need to create 2 arrays, each with 4 elements. One array contains four int values gotten from the user, and the other array contains pointers to the elements of the first array. I keep getting the following error:
array type 'int *[4]' is not assignable
on this line:
my_ptrs = &my_ints;
Here is my code:
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int my_ints[4];
int *my_ptrs[4];
float temp;
int num;
for (int x=0; x< 4; x++)
{
cout << "Enter Integer:" << endl;
cin >> num;
my_ints[x] = num;
}
my_ptrs = &my_ints;
for(int k=0; k<=3; k++)
{
for(int j=k+1; j<=3; j++)
{
if(my_ptrs[k]>my_ptrs[j])
{
temp=*my_ptrs[k];
my_ptrs[k]=my_ptrs[j];
*my_ptrs[j]=temp;
}
}
cout << my_ptrs[k] << " ";
}
return 0;
}

Your apparent intent is to have each pointer in my_ptrs to point to the corresponding value in my_ints.
I'm afraid there are no shortcuts here, using a single assignment. You have to do it the hard way:
for (int i=0; i<4; ++i)
my_ptrs[i]=&my_ints[i];

You cannot assign a pointer-to-an-array to an array variable, like you are trying to do. But what you can do instead is either:
initialize the second array in its declaration directly:
int my_ints[4];
int* my_ptrs[4] = {&my_ints[0], &my_ints[1], &my_ints[2], &my_ints[3]};
populate the array in a separate loop:
int my_ints[4];
int* my_ptrs[4];
for (int i = 0; i < 4; ++i)
my_ptrs[i] = &my_ints[i];
That being said, based on what you are trying to do ("i want to print the my_ptrs array in ascending order"), you could just get rid of the second array altogether and use the std::sort() algorithm instead:
Sorts the elements in the range [first, last) in ascending order.
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int my_ints[4];
for (int x = 0; x < 4; ++x)
{
cout << "Enter Integer:" << endl;
cin >> my_ints[x];
}
std::sort(my_ints, my_ints+4);
for(int k = 0; k < 4; ++k)
cout << my_ints[k] << " ";
return 0;
}

Related

Want to reverse an array of numbers C++

I have some code written but I'm not sure why the reversed array is not giving me the exact values I need. I created a second array the same size as the first and used nested for loops to fill the second with the contents of the first in reverse.
See below:
#include <iostream>
using namespace std;
int main()
{
// Ask for how big the array is
int n;
cout << "how big is the array?" << endl;
cin >> n;
// create array
int a[n];
// create second array
int b[n];
// ask for contents of the 1st array
cout << "what's in the array?" << endl;
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
// reverse the array
for (int i = n - 1; i >= 0; i--)
{
for (int k = 0; k < n; k++)
{
b[k] = a[i];
break;
}
}
// print out the new array
for (int k = 0; k < n; k++)
{
cout << b[k] << endl;
}
return 0;
}
you don't need 2 bucles for fill the second array
try with:
//reverse the array
s = 0;
for (int i=n-1;i>=0;i--){
b[n]=a[s];
s++;
}
Try something like this:
#include <algorithm>
#include <iostream>
#include <vector>
namespace {
template <typename IStream>
[[nodiscard]] int readOneIntFrom(IStream& istream) {
int x;
istream >> x;
return x;
}
}
int main()
{
// Ask for how big the array is
std::cout << "how big is the array?" << std::endl;
auto n = readOneIntFrom(std::cin);
// create array
std::vector<int> a;
// ask for contents of the 1st array
std::cout << "what's in the array?" << std::endl;
for (int i = 0; i < n; i++)
{
a.emplace_back(readOneIntFrom(std::cin)); // Make a new entry at the end of a.
}
// Construct b from a backward. (Or do auto b = a; std::reverse(b.begin(), b.end());
auto b = std::vector<int>(a.rbegin(), a.rend());
// print out the new array
for (const auto& bi : b)
{
std::cout << bi << std::endl;
}
return 0;
}

when inputting a array the length of array replacing the first element in the array in c++ [duplicate]

This question already has answers here:
How do I use arrays in C++?
(5 answers)
Closed 1 year ago.
When inputting a array in c++ the element in 0th position will become the length of the array.
have two functions to input and print the array when print function calls the output array has always the array length in 0th position.
#include<iostream>
using namespace std;
int getArray(int array[])
{
int len;
cout << "Enter the length of the array" << endl;
cin >> len;
cout << "Enter the elements in the array" << endl;
for (int i = 0; i < len; ++i)
{
cin >> array[i];
}
return len;
}
void printArray(int array[], int len)
{
for (int i = 0; i < len; i++)
{
cout << array[i];
}
}
int main(int argc, char const *argv[])
{
int array[] = {};
int len = getArray(array);
printArray(array, len);
return 0;
}
In C++, the size of an array must be a compile time constant. So you cannot write code like:
int n = 10;
int arr[n]; //incorrect
Correct way to write this would be:
const int n = 10;
int arr[n]; //correct
For the same reason the following code (last statement) is incorrect :
int k;
cin >> k;
int arr[k]; //incorrect because k must be a compile time constant
You can see that this results in a problem here.
You should use std::vector for this purpose.
Using std::vector, your implementation would look like:
#include<iostream>
#include <vector>
using namespace std;
//passing vec by reference
int getArray(std::vector<int> &vec)
{
int len;
cout << "Enter the length of the vector" << endl;
cin >> len;
cout << "Enter the elements in the vector" << endl;
int element;
for (int i = 0; i < len; ++i)
{
cin >> element;
vec.push_back(element);//use push_back to add element to vector
}
return len;
}
//passing vec by reference
void printArray(std::vector<int> &vec, int len)
{
for (int i = 0; i < len; i++)
{
cout << vec[i]<<std::endl;//use vec[i] to access ith element
}
}
int main()
{
std::vector<int> vec;
int len = getArray(vec);
printArray(vec, len);
return 0;
}
You can see the output here.
Note
You can simply take the input in the main() itself instead of calling another functions. Similarly for printing the vector. But i have given the code according to your implementation.

How to debug my C++ program?

I try to enter 2d array and to sum all numbers in one row. Then I convert that number to binary (8 bit) and to set it again in new 2d array. Here's my code. I get output in negative numbers and I expect binary number.
I input
1 2 3
4 5 6
7 8 9
And i want this output
00000110
00001111
00011000
i get
00000000
00000000
00000000
#include<iostream>
using namespace std;
int main()
{
int n,m,j,i;
int a[50][50],b[50][8],c[50];
cin>>n>>m;
for(i=0;i<n;i++)
{
c[i]=0;
for(j=0;j<m;j++)
{
cin>>a[i][m];
cin.ignore();
c[i]+=a[i][j];
}
}
for(i=0;i<n;i++)
for(j=0;j<8;j++)
{
b[i][j]=c[i]%2;
c[i]/=2;
}
for(i=0;i<n;i++)
{
for(j=0;j<8;j++)
{
cout<<b[i][j];
}
cout<<endl;
}
}
I attempted to revise your code but I soon realised that you were doing some weird unnecessary things so I just started fresh and here's what I've got for you:
#include <iostream>
#include <vector>
using namespace std;
void add_array(int arr1[], int arr2[], int arrLength, int ret[]) {
for(int i = 0; i < arrLength; i++) {
ret[i] = arr1[i]+arr2[i];
}
return;
}
void to_binary(int n, vector<int> *ret) {
while(n!=0) {
ret->push_back(n%2==0 ?0:1);
n/=2;
}
}
int main() {
int a[5] = {1,2,3,4,5};
int b[5] = {6,7,8,9,10};
int c[5];
add_array(a, b, 5, c);
cout << "A:" << endl;
for(int i = 0; i < 5; i++) {
cout << i << " : " << a[i] << endl;
}
cout << "B:" << endl;
for(int i = 0; i < 5; i++) {
cout << i << " : " << b[i] << endl;
}
cout << "C:" << endl;
for(int i = 0; i < 5; i++) {
cout << i << " : " << c[i] << endl;
}
vector<int> vec;
for(int i = 0; i < 5; i++) {
to_binary(c[i], &vec);
for(int j = 0; j < vec.size(); j++) {
cout << vec[j];
}
cout << endl;
vec.clear();
}
return 0;
}
I don't know how you were handling the adding of the two functions so I just wrote a really simple function there, I'll start with the parameters
int arr1[], int arr2[]
These are the two functions you'll be adding, simple.
int arrLength
This tells the function what the length of the two arrays is for the 'for loop'
int ret[]
Ret is the return array and is passed in so that it can be modified with the added arrays, now you could do that with either of the other two arrays but this is better practice especially if you want to reuse the other arrays later.
Now here's the function itself
for(int i=0;i<arrLength;i++){ ret[i]=arr1[i]+arr2[i];}
Here we loop through each position in the arrays and place them in the variable 'ret', this is the whole thing.
The function
void to_binary(int n, vector<int> *ret)
handles the decimal to binary using a vector for variable sizes, it's basically what you were doing just in a function.
In the function main we create the three arrays and call add_array with the necessary arguments, then we create the vector vec and then proceed to loop through the array c getting the binary number of each position and then since we stored the binary number in an int vector instead of a string we loop through the vector
for(int j = 0; j < vector.size(); j++)
We are using vector.size() to get the dynamic size of the vector, then we print out each binary digit and then print an endl and clear the vector for reuse.

Max In a C++ Array

I am trying to find the 'biggest' element in a user made array ,by using the max function from the algorithm library/header.
I have done some research on the cplusplus reference site but there I only saw how to compare two elements using the max function. Instead I am trying to display the maximum number using a function 'max' ,without having to make a 'for' loop to find it.
For example:
Array: array[]={0,1,2,3,5000,5,6,7,8,9}
Highest value: 5000
I have made this code but it gives me a bunch of errors, which can be the issue?
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int array[11];
int n = 10;
for (int i = 0; i < n; i++) {
array[i] = i;
}
array[5] = 5000;
max(array , array + n);
for (int i = 0; i < n; i++)
cout << array[i] << " ";
return 0;
}
max_element is the function you need. It returns an iterator to the max element in given range. You can use it like this:
cout << " max element is: " << *max_element(array , array + n) << endl;
Here you can find more information about this function: http://en.cppreference.com/w/cpp/algorithm/max_element
Here is a modification of your program that does what you want:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int array[11];
int n = 11;
for (int i = 0; i < n; i++) {
array[i] = i;
}
array[5] = 5000;
cout << *std::max_element(array, array + n) << "\n";
return 0;
}
Note that you had a bug in your program, you did not initialize the last element in your array. This would cause your array to contain junk value in the last element. I've fixed that by increasing n to 11. Note that this is OK because the condition in the for loop is i < n, which means that i can be at most 10, which is what you want.
You can also use std::array by #include<array>
#include <iostream>
#include <algorithm>
#include <array>
using namespace std;
int main()
{
array<int,10> arr;
int n = 10;
for (int i = 0; i < n; i++) {
arr[i] = i;
}
arr[5] = 5000;
cout<<"Max: "<< *max_element(arr.begin(),arr.end())<<endl;
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
More info on std::array

C++ How to change the output on a new array

So I wrote a program that is supposed select the perfect squares from an array and put it into another array. Example: (2,4,13,5,25,66) and the second array(the result) should look like this (4,25)
My result looks like this (0,4,0,0,25,0) ...so its half good ...how to make it show only 4,25 ?
#include<iostream.h>
#include<math.h.>
int main()
{
int A[100],i,n,p,j;
cout << "Number of array elements=";
cin >> n;
for(i=1;i<=n;i++)
{
cout<<"A["<<i<<"]=";
cin>>A[i];
}
for(i=1;i<=n;i++)
{
p=sqrt(A[i]) ;
if(p*p==A[i])
A[j]=A[i];
else
A[i]=0;
cout << A[i] << " ";
}
return 0;
}
USING ONLY c++ basic commands...as i did
You need to keep a separate count of how many perfect squares you've found and use that to place your answers into an array of perfect squares:
int squares[???];
// ...
if(p*p==A[i]) {
squares[squaresFound]=A[i];
squaresFound++;
}
The problem now will be to decide how long the squares array should be. You don't know ahead of time how many squares you're going to get. Are you going to have it the same size as A and fill the rest with 0s? Or do you want the array of squares to be exactly the right size?
If you want it to be the right size, you're much better off using a std::vector:
std::vector<int> squares;
// ...
if(p*p==A[i]) {
squares.push_back(A[i]);
}
But I think your silly "only basic C++ commands" restriction will not allow you to do this.
You talk about a second array (the result), yet your code declares only one array! Additionally, you reference A[j], but your j has not be initialized.
You should declare another array B[100], initialize j to zero, and then use this code when you find a square:
int j = 0;
for (int i=0 ; i != n ; i++) {
int p = sqrt(A[i]);
if(p*p==A[i]) {
B[j++] = A[i];
}
}
Make another array, remove all occurrences of 0 from the resultArray and add non-0 to newArray.
OR
int j=0
if(A[i]==p*p)
squares[j++]=A[i];
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
int A[100];
int n;
cout << "Number of array elements = " << endl;
cin >> n;
for(int i = 0; i < n; i++)
{
cout << "A[" << i << "] = ";
cin >> A[i];
}
int B[100];
int cnt_sqr = 0;
for(int i = 0; i < n; i++)
{
int p = sqrt(A[i]);
if (p * p == A[i])
{
B[cnt_sqr++] = A[i];
}
}
for (int i = 0; i < cnt_sqr; i++)
{
cout << B[i] << ' ';
}
return 0;
}
Full code of that about what you were told above
If you do not want to modify your code you can write the following:
for(i=1;i<=n;i++)
{
p=sqrt(A[i]) ;
if(p*p==A[i])
{
cout << A[i] << " ";
}
}
It will print you only perfect squares.
If you want to copy elements to another array:
int squares[100] = {0}; // Assuming that all values can be perfect squares
int square_count = 0;
for(i=1;i<=n;i++)
{
p=sqrt(A[i]) ;
if(p*p==A[i])
{
squares[square_count++] = A[i];
}
}