C++ Find maximum element of an array USING ONLY POINTERS - c++

I have an assignment where I have to find the max and min element of an array using only pointers. The directions say you have to use pointers for everything but didn't make it clear if you can make variables then just not use them and make pointers pointing to them or if there literally cant be one regular variable declaration in the program.
I already did the whole assignment by declaring variables then making pointers point to them but just to be safe I'm redoing it with no variables.
The only thing I'm having trouble with is making a for loop with only pointers because there is no variable set to 0 that I can make a pointer point to and get the memory address of 0 to start the counter.
I would just do this:
int i = 0;
int *counterptr = &i;
cout << "Please input the array values" << endl;
for (*counterptr ; *counterptr < 10; *counterptr += 1)
{
}
But since I cant make variable i to point to I don't know how to get the memory address of 0 to use for the pointer. This is what I have right now but I don't know what to make counterptr equal to.
float nums[10];
int *counterptr = ;
float *maxptr, *minptr, *difference;
maxptr = &nums[0];
minptr = &nums[0];
cout << "Please input the array values" << endl;
for (*counterptr ; *counterptr < 10; *counterptr += 1)
{
cin >> nums[*counterptr];
if (nums[*counterptr] > *maxptr)
{
maxptr = &nums[*counterptr];
}
if (nums[*counterptr] < *minptr)
{
minptr = &nums[*counterptr];
}
}
Any help would be appreciated thank you.

corrected program snippet given below. It can be written better, but I modified for your understanding from your code changed to work now. counterptr is a pointer within the array elements (as an iterator), *counterptr will be one of the elements, similarly *minptr and *maxptr are minimum and maximum elements whereas, minptr and maxptr are respective pointers to minimum and maximum elements within the array of floating point numbers. Hope this helps.
float nums[10];
float *counterptr;
float *maxptr, *minptr, *difference;
maxptr = &nums[0];
minptr = &nums[0];
cout << "Please input the array values" << endl;
for (counterptr = nums, counterptr < nums + 10; counterptr++)
{
cin >> *counterptr;
if (*counterptr > *maxptr)
{
maxptr = counterptr;
}
if (*counterptr < *minptr)
{
minptr = counterptr;
}
}

Related

How do you build an array with certain elements from another array in C++?

Given a one-dimensional array with n integers and a whole number A,
list how many elements are larger than A
and build an array with these elements.
I'm having problems with the last part.
The answer is almost already in the question
(giving it here, assuming that the question is really as simple as it confusingly seems to me):
count the relevant elements, print/"list" that number
create a new std::array of that size
(consider asking whether using a std::vector is an option, it would allow doing this in a single pass)
(explicitly do NOT attempt to use the non-C++ construct of C-style VLA, variable length arrays, like std::cin>>n; int NewArray[n];)
go through the input array again and copy the relevant elements to the new array
count indexes in both arrays separatly, because the index in the first array will soon be larger than the index into the new array
Note:
I intentionally do NOT provide code, because I feel that the compromise described here should be applied: How do I ask and answer homework questions?
First you have to create two arrays (if you can use std::vectors, i think they will work nicely in this scenario) - first one as a base, and the second one for storing values larger than A.
Get input of A and n.
Use a for loop to put n values into the base array.
Use a for loop to check if baseArray[i] is bigger than A, if true - put baseArray[i] into the second array (if youre using std::vectors do it by push_back()).
Display the number of values higher than A by secondArray.size().
Without using the std::vector:
#include <iostream>
using namespace std;
int main()
{
int n;
int A;
int howManyBiggerThanA = 0;
cin >> n;
cin >> A; //you haven't specified how the n and A are supposed to be implemented so ill assume its going to happen this way
int *array = new int[n]; //creating an array with n integers
array[0] = A; //assigning A to the array as specified in the question - "and a whole number A"
for (int i = 1; i < n; i++)
{
array[i] = i; //filling the array with n integers of value 1 to n-1 (u havent specified what values are supposed to be inside this array)
}
for (int i = 0; i < n; i++)
{
if (array[i] > A)
{
howManyBiggerThanA++; //determining how many values are bigger than A
}
}
int *arrayForBiggerThanA = new int[howManyBiggerThanA]; //creating an array for values that are bigger than A
int assistant = 0;
for (int i = 0; i < n; i++)
{
if (array[i] > A)
{
arrayForBiggerThanA[assistant] = array[i]; //filling the second array with elements that are bigger than A
assistant++;
}
}
cout << "How many elements bigger than A: " << howManyBiggerThanA << endl;
cout << "Values bigger than A: ";
for (int i = 0; i < howManyBiggerThanA; i++)
cout << arrayForBiggerThanA[i] << ", ";
delete[] array;
delete[] arrayForBiggerThanA;
return 0;
}

Invalid conversion error when trying to keep array from changing when called by a function

For this assignment, I need to make a sorted copy of an array the user has given values to. All of my code works as intended, except for this specific part. I need this function (sortedCopy) to print out the sorted version of their array, without actually changing the array itself. As far as I can tell, to do so I need to used a constant version of the array in the function so the prototype would be something like: int *sortedCopy(const int *array, int size), but all this does is give the error shown in the title. Specifically:
main.cpp:72:29: error: assignment of read-only location '*(array +
((sizetype)(((long unsigned int)i) * 4)))' array[i] = array[min]
and it does this error twice, except with array[min] = temp; at the end instead
This is the code used, with the relevant parts of main:
#include <iostream>
using namespace std;
int* sortedCopy(const int *array, int size) {
int i, j, min, temp;
for (i = 0 ; i < size - 1; i++) {
min = i;
for (j = i + 1; j < size; j++) {
if (array[j] < array[min]) {
min = j;
}
}
temp = array[i];
array[i] = array[min];
array[min] = temp;
}
cout << "Sorted array is: " << endl;
for(int i = 0; i < size; i++) {
cout << array[i] << " ";
}
cout << endl;
// Not sure if I need to return anything or not either
}
int main() {
cout << "Please enter the size of the array." << endl;
int arraySize;
int array[arraySize];
cin >> arraySize;
cout << "Please enter integer values until the array is filled." << endl;
for (int i = 0; i != arraySize; i++) {
cout << "Value " << (i + 1) << ": ";
cin >> array[i];
cout << endl;
sortedCopy(array, arraySize);
for (int i = 0; i != arraySize; i++) { // I want this part to print the
cout << array[i] << " "; // original array entered by the user
}
}
If I remove the const part of the function, it works totally fine, except it will print the sorted array after the function is called, instead of the original array.
Firstly, C/C++ is best read "top-down":
int arraySize;
int array[arraySize]; // arraySize is undefined here!!
cin >> arraySize;
On the second line, ArraySize, might be 1, or 0, or -1000. You haven't defined it until line 3.
Also, C++ doesn't allow you to allocate arrays of variable size (unless that size is const [ so it is known at compilation time]):
int array[4];
The above is fine. This helps the operating system know how much memory to provide for you on the stack (it needs to do this before your programme starts running).
const int arraySize = 4;
int array[arraySize];
Because the C++ compiler knows that arraySize is 4, it processes this just like the above code, so this is also fine.
So to handle arrays of genuinely variable length (length that depends on inputs), you need to first read the user inputs, then use dynamic allocation ("new", or a container that does dynamic allocation for you, like a vector).
As for the problem with "const", what I think that you need to understand here is that "const" is really just a promise from the programmer: The programmer is communicating to the compiler (and any programmers reading the code) that this data is not supposed to change. All the compiler does is check whether you keep your promise (or if you send it to another function / pointer that doesn't hold that promise). So by using "const" there is no work done being done for you to actually keep the data constant - just that it will complain if you don't do the work.
int* sortedCopy(const int *array, int size) {
Above you're flagging to the compiler that the sortedCopy function will keep the data in the array constant.
array[i] = array[min];
array[min] = temp;
And here (above) you are breaking that promise.
If you don't want to edit the original array, then the easiest solution is just to copy it before you send it to your sorting function.

segmentation fault with pointer array

I am a getting a segment fault when trying to input data for my array of pointers. Im pretty new to coding so any help would be great. My task was to make an array of pointers then display, swap them around and than sort them
#include <iostream>
using namespace std;
float getValueFromPointer(float* thePointer)
{
return *thePointer;
}
float* getMinValue(float* a, float* b)
{
if (*a < *b)
{
return a;
}
else
{
return b;
}
}
int main()
{
int arraySize;
cout << "Enter the array size: ";
cin >> arraySize;
float** speed = new float*[arraySize]; // dynamically allocated array
for(int i = 0; i < arraySize; i++)
{
cout << "Enter a float value: ";
cin >> *speed[i];
}
// Core Requirement 2
for (int i = 0; i < arraySize; i++)
{
float value = getValueFromPointer(*speed+i);
cout << "The value of the element " << i << " is: ";
cout << value << endl;
}
//float *pointerToMin = getMinValue(&speed[0], &speed[arraySize - 1]);
//cout << *pointerToMin << endl;
delete [] speed;
speed = NULL;
return 0;
}
You’ve only allocated space for the outer array but you need to also allocate space for each of the internal floats.
So before calling this line:
cin >> *speed[i];
You need to first allocate space for it:
speed[i] = new float;
Your problem is that you've allocated an array of float pointers. You need to allocate an array of floats. So currently you have no memory allocated for the actual floats. If you do this, you'll allocate that memory:
float *speed = new float[arraySize];
You don't have any need for a 2D/jagged array that I can see. If you start with the code above, the compiler errors should lead you right in the direction. (Basically you will start removing * from a lot of places in your code.)
EDIT
Based on your requirement that I misunderstood, a possible approach is the following. The other answer (the one that isn't mine) makes sense in broader scenarios than this, but hopefully this is sort of another angle to think about that rather arbitrary problem you're trying to solve:
int main()
{
float *pFloats = new float[10];
float **ppFloats = new float*[10];
//assign float values and pointers to them in same loop
for (int i = 0; i < 10; i++)
{
pFloats[i] = i;
ppFloats[i] = &pFloats[i];
}
//swap two arbitrary pointers
float *pTemp = ppFloats[4];
ppFloats[4] = ppFloats[5];
ppFloats[5] = pTemp;
//print our float array
for (int i = 0; i < 10; i++)
printf("%f\n", pFloats[i]);
//print our float array *through* our pointers
for (int i = 0; i < 10; i++)
printf("%f\n", *ppFloats[i]);
delete[] ppFloats;
delete[] pFloats;
}
Ignore the hard-coded constants, etc...The point here is that I've created a contiguous memory area for the floats, and then created an array of float pointers on top of it. Note that I can sort my pointer array with zero impact on the original array. There are much smarter ways to do this, but...looks like you're learning about raw pointers, so...
Contrast with the other answer which creates jagged memory for the floats (1 at a time, on demand, not necessarily contiguous).

Homework: Making an array using pointers

I have a homework problem that I'm working out. Me and some other students are pretty sure that our teacher misspoke, but maybe not. I checked through a bit of the questions here already and can't really find a way to use pointers to create what is essentially an array. The instructions read as follows.
Rewrite the following program to use pointers instead of arrays:
The code is this
int main()
{
int salary[20];
int i;
for (i = 0; i < 20; i++)
{
cout << "Enter Salary: ";
cin >> salary[i];
}
for (i = 0; i < 20; ++i)
salary[i] = salary[i] + salary[i] / (i + 1);
return 0;
}
My solution was this:
int main()
{
int* salary_pointer = new int;
for (int i = 0; i < 20; i++)
{
cout << "Enter Salary: ";
cin >> *(salary_pointer + i);
}
for (int i = 0; i < 20; ++i)
{
*(salary_pointer + i) = *(salary_pointer + i) + *(salary_pointer + i) / (i + 1);
cout << *(salary_pointer + i) << endl;
}
delete salary_pointer;
return 0;
}
It keeps flagging a segmentation fault at about salary number 13
My main purpose (because I'm almost positive my teacher wrote this down wrong) is to understand more about pointers, so any and all tips and tricks for learning these confusing things would be greatly appreciated. Thank you all!
Use
int* salary_pointer = new int[20];
instead, as you allocate 20 ints, not just one. Then, delete the dynamic array using
delete[] salary_pointer;
instead of delete salary_pointer. Be also careful here:
salary[i] / (i + 1);
If the operands are int, then you end up with truncation. Use salary[i]/(i + 1.) in case you want your result as a double (in which case you better make salary an array of doubles or a pointer to double so you don't have this issue anymore).
Your teacher did not misspeak. You have bugs in your program.
How many elements did you allocate?
How many elements are you trying iterate through and dereference?
How many elements did you free?
You're getting a seg fault, because you are dereferencing memory you did not allocate.
I'd be more specific, but giving too much away won't help you get better when it comes to homework.
This kind of manual memory management is done away with later when you will be using STL containers for the most part, but the relationship between pointers and arrays, and the ability to do pointer arithmetic is important.
Why is your teacher wrong?
Here is what is happening. You are creating a pointer to a SINGLE integer. As you iterate through your for loop what you are doing is actually overwriting memory that is possibly, and I STRESS possibly, being used by other bits of your program. This causes undefined behavior up to and including a crash.
Redo your memory allocation and your access violation should go away. Also, use a variable to hold your '20'. Something like const int MAX_SALARIES = 20. Learn to do this as it will often save you TONS of headaches in the future.
In this statement
int* salary_pointer = new int;
there is allocated only one object of type int.
And as there is used the division operation it is better to use type float instead of int for the array.
I would suggest the following solution. It uses only pointers.
#include <iostream>
int main()
{
const size_t N = 20;
float *salary = new float[N];
^^^^^^^^^^^^^^^^^^^^^^^^^^
for ( float *p = salary; p != salary + N; ++p )
{
std::cout << "Enter Salary: ";
std::cin >> *p;
}
for ( float *p = salary; p != salary + N; ++p )
{
*p += *p / ( p - salary + 1 );
}
delete [] salary;
^^^^^^^^^^^^^^^^
return 0;
}

Storing array's of integers on the heap and accessing them via pointers

I'm hoping someone can shed some light on where I am going wrong with pointers.. I've read countless web pages and tried various things but for some reason my code is returning jibberish (which I'm guessing may be the memory addresses instead of the data within my array). The purpose of the program is to create an array of 100 elements on the heap, pass this array by a pointer to a function (along with two integer variables start and end); a new array will be created on the heap (this comprises of a chunk of the original array using the start and end variables) and the pointer to this array is passed back to the main method so that the new array can be outputted. My problem is not only is the output seeming to be the location not the value, but also it seems 100 values are outputted not 20 as should be expected. I've spent hours trying to figure out where I have gone wrong and just when I think I understand the concept of pointers my faith is destroyed by red squigglies and incorrect outputs. Please HELP! My code is as follows:
#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
double* getSubArray(double*, int, int);// Declare a function that will get the sub array
int _tmain(int argc, _TCHAR* argv[])
{
const int size = 100;// Declare the size of the array
double* pA;// Declare the variable to hold the pointers to the data in array
double* pB;
int start = 15;
int end = 35;
pA = new double[size];// Create space for the array
srand(clock());// Seed the program to the computers current time so that random gets a different set of random numbers everytime it is run
// Use a for loop to traverse through each element of the array (starting at index 0) placing a number defined by the random function that is no higher than 250
for (int i = 0; i < size; i++)
{
pA[i] = rand()%250;
}
cout << "An Array of 100 numbers is created and stored in the heap, these values are:" << endl;
// Output the Array for the user to see
for (int j = 0; j < size; j++)
{
// Place 10 numbers on each line
if (j % 10 == 0)
{
cout << endl;
}
cout << *(pA + j) << " ";
}
cout << endl << "The program will build a second array using the data between the indexes " << start << " & " << end << endl;
pB = getSubArray(pA, start, end);// Pass the data to the method
// Output second array for user to compare
for (int k = 0; k < size; k++)
{
// Place 10 numbers on each line
if (k % 10 == 0)
{
cout << endl;
}
cout << *(pB + k) << " ";
}
system("pause");
return 0;
}
double* getSubArray(double* pA, int start, int end)
{
double* pB = new double[end-start];// Declare space in the heap for the new array whoes size is the size of the criteria given
for (int i = 0; i < (end - start); i++)
{
for (int j = start; j < end; j++)
{
*(pB + 0) = pA[j];
}
}
return pB;
}
*(pB + 0) = pA[j];
That keeps writing to the first element of the array. Surely you want to write to each element in turn:
for (int i = start; i < end; ++i) {
pB[i-start] = pA[i];
}
or if you don't want to write your own loop
std::copy(pA+start, pA+end, pB);
Don't forget to delete[] everything you new[] or, to save mucking around with low-level memory management, use std::vector to manage the dynamic arrays for you.