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;
Related
So it's a simple c++ program which takes 2 sorted arrays from user dynamically using new operator and sum ups their size to create a third array which is equal to the length of the both array sum..
Like final_arr = arr1_size +arr2_size;
Everything is working fine but the problem is that is that I am taking array values from user so I need to check up that array entered by user is sorted or not, if array is not sorted then program must take that array values from user until he entered in correct order. I am using label with goto statement for checking the array, if some element smaller than previous element is found, then we will go at the top of the for loop through goto statement..as shown in code below.
//receiving array 1 input from user dynamically...
cout << "How many numbers you want to enter for array 1" << endl;
cin >> arr1_size;
arr1 = new int [arr1_size]; //creating array dynamically
arr1_label: //goto label
cout << "Enter numbers " << endl; //just to display
for (int i = 0; i < arr1_size; i++) { //loop for taking value from the user for arr1
cin >> arr1[0];
}
for (int i = 1; i < arr1_size; ) {//loop for checking for unordered array, if detects restart the input for loop
if (arr1[i--] > arr1[i]) {
cout << "Array 1 is not sorted" << endl;
goto arr1_label;
break;
}
i++;
}
It's a task in which I can't use vector ... I only have to use arrays dynamically.....Complete code of project is given below..
int main()
{
int arr1_size, arr2_size, final_arr_size;
int* arr1; int* arr2; int* final_array;
//receiving array 1 input from user dynamically...
cout << "How many numbers you want to enter for array 1" << endl;
cin >> arr1_size;
arr1 = new int [arr1_size]; //creating array dynamically
arr1_label: //goto label
cout << "Enter numbers " << endl; //just to display
for (int i = 0; i < arr1_size; i++) { //loop for taking value from the user for arr1
cin >> arr1[0];
}
for (int i = 1; i < arr1_size; ) {//loop for checking for unordered array, if detects restart the input for loop
if (arr1[i--] > arr1[i]) {
cout << "Array 1 is not sorted" << endl;
goto arr1_label;
break;
}
i++;
}
//receiving array 2 input from user dynamically...
cout << "How many numbers you want to enter for array 2" << endl;
cin >> arr2_size;
arr2 = new int[arr2_size];
cout << "Enter numbers " << endl;
for (int i = 0; i < arr2_size; i++) {
cin >> arr2[i];
}
//Merged array code here...
final_arr_size = arr1_size + arr2_size;
final_array = new int[final_arr_size];
int i = 0, j = 0, k = 0;
while (i < arr1_size && j < arr2_size) {
if (arr1[i] < arr2[j]) {
final_array[k++] = arr1[i++];
}
else {
final_array[k++] = arr2[j++];
}
}
while (i < arr1_size) {
final_array[k++] = arr1[i++];
}
while (j < arr2_size) {
final_array[k++] = arr2[j++];
}
//displaying final array
for (int i = 0; i < final_arr_size; i++) {
cout << final_array[i] << " ";
}
//deleting dynamically allocated memory.
delete[] arr1;
delete[] arr2;
delete[] final_array;
return 0;
}
#include <algorithm>
// ...
// check if arr1 is sorted
bool input_is_sorted = std::is_sorted(arr1, arr1 + arr1_size);
See https://en.cppreference.com/w/cpp/algorithm/is_sorted
Of course you would better replace bare pointers with std::vector etc.
Im having trouble with the syntax here. We are studying structures and pointers in class currently and are tasked with creating a dynamic array of a single structure with a pointer array inside to both be allocated and deleted by the end of the program. (Hopefully that made sense)
Here are the snippits of code im working with, note how the entry of scores works:
std::cin << stuArray[i].stuScore[j]
But then the deletion in a similar manner, does not:
delete[] stuArray[count].stuScore[j];
Deletion Code:
do
{
for (unsigned short j = 0; j < numTests; j++)
{
delete[] stuArray[count].stuScore[0]; //Syntax???????
}
count++;
} while (count < numStudents);
delete[] stuArray;
Score Entry Code (Which Works)
bool ScoreEntry(Student * stuArray, unsigned short numStudents, unsigned short numTests)
{
//Local Variables
unsigned short idTempChoice = 0;
//Get Id Number
std::cout << "\nChoose a student by ID and enter the test scores: ";
std::cin >> idTempChoice;
//Id lookup
for (unsigned short i = 0; i < numStudents; i++)
{
//Id Check
if (idTempChoice == stuArray[i].stuId)
{
std::cout << "Student selected: " << stuArray[i].stuName << std::endl;
//Score Entry
for (unsigned short j = 0; j < numTests; j++)
{
std::cout << "Test " << j + 1 << "'s Score: ";
std::cin >> stuArray[i].stuScore[j];
}//End For Loop j
return true;
}
}//End For Loop i
//Student Id not found
std::cout << "Student not found!\n";
return false;
}
Allocation Code (Struct):
void MemAllocation(Student * &stuArray, unsigned short &numStudents)
{
//Get Number of students
std::cout << "How many students have taken the test: ";
std::cin >> numStudents;
std::cout << std::endl;
//Dynamically allocate pointers
stuArray = new Student[numStudents];
}
Allocation Code (Pointer inside struct):
for (unsigned short i = 0; i < numTests; i++) //Allocate Dynamic array for each student
{
stuArray[i].stuScore = new float[numTests];
}
This is Literally all the code you need reference, this is not a bug its a syntax problem :)
Try delete[] stuArray[count].stuScore;
not delete[] stuArray[count].stuScore[j];
delete [] is made to delete an array allocated with new type[n]
You want to delete the pointer to the memory, not the actual memory.
You can delete delete[] stuArray[count].stuScore but not delete[] stuArray[count].stuScore[j] - drescherjm
Fixed using:
do
{
delete[] stuArray[count].stuScore;
count++;
} while (count < numTests);
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)
I am trying to create a program that asks the user for a set of numbers, first asking for the quantity of numbers, then having them input all the numbers. The program then checks the numbers, and determines whether or not the numbers given are in ascending order or not. Then, simply print out "yes ascending" or "no not ascending" and print out the array on one line..So far, my code will just always say that "yes, this is an increasing array!" Please look below for my code. Thanks in advance!..
tested: 1 2 3 4 5 6 --> pass
1 3 5 2 4 6 --> fail (still says it is an ascending array)
#include <iostream>
#include <string>
using namespace std;
bool isAscending(int arr[], int size)
{
for (int i=0; i < size-1; i++)
{
if (arr[i] > arr[i+1])
{
return false;
}
}
return true;
}
int main()
{
int arraysize = 0;
string numbers;
cout << "Enter the size of the array: " << endl;
cin >> arraysize;
if (arraysize < 1)
{
cout << "ERROR: you entered an incorrect value for the array size!" << endl;
}
cout << "Enter the numbers in the array, separated by a space, and press enter: " << endl;
numbers += ' ' + numbers;
cin >> numbers;
int arr[arraysize];
if ( isAscending(arr, arraysize))
{
cout << "This IS an increasing array!" << endl;
}
else
{
cout << "This is NOT an ascending array!" << endl;
}
for (i = 0; i < arraysize - 1; i++)
{
cout << arr[i];
}
return 0;
}
You're reading in "numbers", which you created as type String.
cout << "Enter the numbers in the array, separated by a space, and press enter: " << endl;
numbers += ' ' + numbers;
cin >> numbers;
Your numbers+= line isn't doing anything except adding a space to your numbers string before your cin happens... I know what you're trying to accomplish, and that won't do it.
Then you're suddenly making an array which, without initializing is filled with garbage, and immediately running isAscending on it:
int arr[arraysize];
if ( isAscending(arr, arraysize)){....}
I advise you declare your array before receiving input, read the input line and process it into INTEGERS, and then add each integer to your array. Here is a (crude) correction of the first section of code in your main that just reads in whitespace separated integers and fills the array with them:
int main(){
int arraysize = 0;
int number = 0;
cout << "Enter the size of the array: " << endl;
cin >> arraysize;
if (arraysize < 1) // you should really have this loop until you get correct input
{ cout << "ERROR: you entered an incorrect value for the array size!" << endl; }
int* arr = new int[arraysize];
cout << "Enter the numbers in the array, separated by a space, and press enter: " << endl;
int i = 0;
while(i < arraysize){
cin >> number;
arr[i] = number;
i++;
};
if ( isAscending(arr, arraysize)){ cout << "This IS an increasing array!" << endl; }
else{ cout << "This is NOT an ascending array!" << endl;}
for (int i = 0; i < arraysize; i++){
cout << arr[i];
if( (i+1) == arraysize){ cout << ". ";}
else cout << ", ";
}
return 0;
}
If you're going to whine about somebody giving partial answers that only address the asker's question, maybe you should take the time to write something yourself.
Is this program OK, or can it be improved (but simply)? How do I make sure no repeat numbers are entered?
int n;
int array[9];
cout<<"Enter Number Between 9-0 Only"<<endl;
for(int i = 0; i<=10; 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;
break;
}
}
(edit) complete, compiling code
To check if the numbers are used with higher performance, try something like this (using the working code from Jack Radcliffe):
#include <iostream>
using namespace std;
int main()
{
int n = 0;
int array[9] = {0};
bool isUsed[10] = {0};
for(int i = 0; i < 9; i++)
{
cout << "Enter Number " << (i + 1) << endl;
cin >> n;
if((n >= 0) && (n <= 9))
{
if (isUsed[n] == false)
{
array[i] = n;
isUsed[n] = true;
}
else
{
cout << "Number has already been used." << endl;
i--;
}
}
else
{
cout << "Numbers from 0-9 only." << endl;
i--;
}
}
return 0;
}
Optimization isn't exactly necessary with this simple of code, but it's this seems to be an exercise of practice, so why not practice optimized code, too?
Most of it is fine, though there are two problems standing out.
First, you have an array of size 9, but you are taking in 11 numbers since you're starting the for loop at 0 and going through to 10.
Second, since you have it so if the entered number is not between 0 and 9, inclusive, the for loop breaks. This entails that fewer than 9 numbers will be put into the array if an invalid number is entered. Change the entire loop to read this and you should be good:
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--;
}
}
The whole fire part was right, but I removed the break in the else-statement and added in the i--. I added that in so when the user is prompted to re-enter the number, the entry number will be at the correct index.
I hope this was helpful.