My program should fill up and show an array. It should also calculate average value in the array.
The program stops at this line:
cin >> *f1[j];
I think it's the problem line, but I could have made mistakes elsewhere.
#include <iostream>
using namespace std;
// prototypes
void add(int*f[],int h);
void show(int*f[],int h);
int average(int*f[],int h);
int main()
{
// getting size of a array
cout << "How many numbers would you insert? : ";
int i = 0;
cin >> i;
cout << endl;
// the dinamic array
int * arr = new int[i];
// call functions
add(&arr, i);
show(&arr, i);
average(&arr, i);
// deleting the dinamic array
delete[] arr;
system("pause");
return 0;
}
// declaring of the functions
// this function should fill up the array
void add(int* f1[], int h)
{
for(int j = 0 ; j < h ; j++)
{
cout << "Insert " << j+1 << ". value : ";
cin >> *f1[j]; //this should be the problem
cout << endl;
}
}
// this function should show the array
void show(int *f2[], int h)
{
for(int j = 0 ; j < h ; j++)
{
cout << *f2[j] << ", ";
}
}
// this function should should show average value of the array
int average(int *f3[], int h)
{
int n = 0;
for(int j = 0 ; j < h ; j++)
{
n += *f3[j];
}
n /= h;
return n;
}
You aren't referencing your arrays correctly. p* points to index p[0]
cout << *f2[j] << ", ";
should be
cout << f2[j] << ", ";
It compiles and runs with the edits I made.
http://ideone.com/DsxOOP
Also, You aren't taking any inputs.
You'll need to:
use int* fX in your function signatures
drop the & referencing from your function calls (you already have a memory address stored in arr and there's no such thing as a memory address for another memory address)
not use * dereferencing within your functions (you're already dereferencing the array with [] indexing)
http://pastebin.com/xY7A6JvE compiles and runs.
Related
#include <iostream>
using namespace std;
int main()
{
int x, y, z;
cout << "how many elements? " << endl;
cin >> x;
int arr[x];
for(int i = 0; i < x; i++)
{
cout << "give number" << endl;
cin >> arr[i];
}
cout << endl;
y = 0;
z = 0;
// for(int i = y; i >= 0; i-z)
while (z < x)
{
for(int i = y; i < x; i++)
{
for(int i = z; i < x-y; i++)
{
cout << arr[i] << " ";
}
cout << endl;
y++;
}
z++;
cout << z;
}
// while (z < x);
return 0;
}
I want my parameter z, which is in the while loop, to link with parameter i=z in the second for loop. I want the program to print numbers from 1 to n, then from 2 to n, and so on, to the moment it will print only n.
Don't mind this cout<<z; in line 30, I was checking if this even works.
I don't know what you mean by "link with z", but here is what the loop should be to do what you want it to:
for (int z = 0; z < x; ++z) // NOTE: get rid of outside z
{
for(int i{z}; i < x; ++i)
std::cout << arr[i] << " ";
std::cout << std::endl;
}
The inner loop loops through all of the values of the array, starting with z and ending at x-1. Since z is incremented, the next loop will start at the next position, starting at what was z plus one and ending at x-1.
Also change:
int arr[x];
To:
int* arr = new int[x];
and add this line at the end:
delete [] arr;
This should be added and changed because C++ doesn't support variable length arrays. However, it does support pointers to blocks of memory treated as arrays. You also should delete memory you use when you are done with it.
In c++, while declaring an array either the size or the elements must be known at the time of compilation, if you want to declare an array during run time, you can do one of the following
you can use std::vector, which is a dynamically growing array, and can be initialized without the size or elements, it is included in the vector header file.
use the new keyword to dynamically allocate a block of memory on the heap which returns a pointer and will act as your array (refer to #captainhatteras 's answer)
However it is better to use vector in this case as it is much more easier to understand and use
And you don't need the nested loop here, (not sure if you were keeping it for future reference, i removed it for the sake of simplicity)
How it works
Here with each iteration of the while loop, we're incrementing the value of int z which is taken as the starting point of our for-loop, therefore with each passing iteration the range of the for-loop is decreased by 1. ultimately the value of int z will be equal to int x and the code will exit the while loop
so your code would look something like this
#include <iostream>
#include <vector>
using namespace std;
int main() {
int x, z = 0;
cout << "how many elements? " << endl;
cin >> x;
vector<int> arr;
for (int i = 0; i < x; i++) {
int choice;
cout << "give number" << endl;
cin >> choice;
arr.push_back(choice);
}
cout << endl;
while (z < x) {
for (int i = z; i < x; i++)
std::cout << arr[i] << " ";
std::cout << std::endl;
z++;
}
return 0;
}
std::vector has a method called push_back() which adds an element passed in to the end of the array
I still have the same problem of wierd number in my arrays, but this time in a different function:
#include <iostream>
using namespace std;
//First Array
int n[20];
int i, a;
//Second Array
int n2[20];
int i2, a2;
void arraySelection();
void printArrays();
void unionArray();
void intersectionArray();
int main(){
arraySelection();
printArrays();
intersectionArray();
unionArray();
return 0;
}
void arraySelection(){
cout << "First array size: ";
cin >> a;
cout << "Array elements: " << endl;;
for (i = 0; i < a; i++){
cin >> n[i];
}
cout << "\nSecond array size: ";
cin >> a2;
cout << "Array elements: " << endl;;
for (i2 = 0; i2 < a2; i2++){
cin >> n2[i2];
}
}
void unionArray(){
const int riemp = 40;
int unionNums[riemp];
int j, x, y, z;
bool t = false;
for (j = 0; j <= riemp; j++){
unionNums[j] = n[j];
cout << unionNums[j] << " ";
}
}
Basically I am trying to copy the numbers of my first array n[20] into my unionNums[40] array. It actually does that but it also outputs a series of 0s and other large wierd numbers. 2 Days in the go and still no idea. (PS If i try to gife fixed numbers to the array, so getting rid of the user input, it goes without any problem whatsoever) I also did not bother copyng my intersectionArray and printArray functions since they do things that I don't need anymore at this point
Here you read in elements up to n[a-1]:
for (i = 0; i < a; i++){
cin >> n[i];
}
So all elements up to n[a-1] are initialized. Then you print all elements up to n[a], however.
for (i = 0; i < a+1; i++){ // note that you have "a+1" here, not just "a"
cout << n[i] << " - ";
}
n[a] wasn't initialized. When you read that out, it's undefined behavior. That often manifests as getting a garbage value, which is what you're seeing in your output. The same thing happens in your second array/loop where you write into the array for i2 < a2 but get output for i2 < a2+1.
I wrote a program for my assignment that involves pointers and dynamic allocation for an array, I am getting a runtime error and the program crashes, there are no compiling errors. Here is the program :
array.h :
#include <iostream>
using namespace std;
void readArray(float*, int &);
void PrintArray(float*, int);
array.cpp :
#include "array.h"
void readArray(float* array, int &size)
{
array = new float[size];
cout << endl;
cout << "Enter the array elements, use spaces: ";
for (int i = 0; i < size; i++)
{
cin >> array[i];
}
cout << endl;
}
void PrintArray(float * array, int size)
{
for (int i = 0; i < size; i++)
{
cout << array[i] << " ";
}
cout << endl;
}
main.cpp :
#include "array.h"
int main()
{
int size = 0;
cout << "How many elements would you like to enter? ";
cin >> size;
cout << endl;
float *array = NULL;
readArray(array,size);
cout << "The array size is " << size << endl;
PrintArray(array, size);
return 0;
}
Sample Output :
How many elements would you like to enter? 3
Enter the array elements, use spaces: 4.0 5.0 6.0
The array size is 3
Crashes here
Can someone let me know what the problem is with the PrintArray function?
The parameter array of readArray() is passed by value, so array in main() remains NULL even if you changed it in readArray(). To make it be passed by reference. In addition, size doesn't need be passed by reference.
change
void readArray(float* array, int &size)
to
void readArray(float*& array, int size)
Q: Can someone let me know what the problem is with the PrintArray function?
A: Your PrintArray function is fine.
The problem is that you never pass the array you've allocated outside of readArray.
BETTER:
float *
readArray(int size)
{
float* array = new float[size];
cout << endl;
cout << "Enter the array elements, use spaces: ";
for (int i = 0; i < size; i++)
{
cin >> array[i];
}
cout << endl;
return array;
}
int main()
...
float *array = readArray(size);
...
NOTES:
If you declared a prototype for readArray() in array.h, you'll need to update it.
There are many ways to accomplish this, but the basic problem is you need ** (a pointer to a pointer) instead of * if you allocate your array inside the function. I believe passing the array pointer back as a function return is arguably the cleanest solution.
IMHO...
not sure if I'm doing this right, or even if I'm allowed to sort using pointers. I made a structure that has pointers to other elements. Then made a vector of this structure, and tried to do some swaps on it.
At first I used dereference operators on the swap operation, but when I did, my sorts were turning out weird, I was getting a bunch of duplicate #'s in the end results (they should all be unique), pulling the dereference off solved this, but it wasn't sorting (unless maybe by memory address).
So here is my code, the area of concern is with the sortSuperStruct function
#include <algorithm> //used for swap, would like to use for sort, but oh well
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
//#include <math.h>
#include <string>
#include <sstream>
#include <vector>
//------------------------------------------------------------------------------
//namespaces?
//------------------------------------------------------------------------------
using namespace std;
//------------------------------------------------------------------------------
//prototypes
//------------------------------------------------------------------------------
struct superStruct
{
//probably not needed
float *percent;
//copy of Dwarf's role pPercent;
float *pPercent;
int *roleName;
int *name;
};
//parallel array to follow along with Dwarf role
struct roles
{
int name;
float priority;
int numberToAssign;
void setRolePriorities ()
{
priority = (float)rand()/(float)RAND_MAX;
}
void setNumberToAssign(int n)
{
numberToAssign = rand() % n + 1;
}
};
//a fit for a role, a Dwarf has this
struct role
{
float percent;
//copy of roles name
int *roleName;
//copy of roles priority
float *rolePriority;
float pPercent;
void set_pPercent()
{
pPercent = percent * (*rolePriority);
};
};
struct Dwarf
{
vector <role> roleValues;
int *maxLabor;
int name;
void setRoleValues(int n, vector <roles> *roleS)
{
srand ( time(NULL) );
//rolesValues
roleValues.resize(n);
//set role %'s
for (int x = 0; x < n; x++)
{
roleValues[x].percent = (float)rand()/(float)RAND_MAX;
//cout << roleValues[x].percent << endl;
//I said I'm pointing to the address value of roleS...
roleValues[x].roleName = &roleS->at(x).name;
roleValues[x].rolePriority = &roleS->at(x).priority;
roleValues[x].set_pPercent();
}
};
};
void initializeSuperStruct(vector <superStruct> *s, vector <Dwarf> *d, int n)
{
//for each Dwarf
int counter = 0;
for (int x = 0; x < d->size(); x++)
{
//for each role
for (int y = 0; y < n; y++)
{
s->at(counter).pPercent = &d->at(x).roleValues[y].pPercent;
s->at(counter).name = &d->at(x).name;
//both are pointers.
s->at(counter).roleName = d->at(x).roleValues[y].roleName;
//cout << d->at(x).roleValues[y].percent << endl;
s->at(counter).percent = &d->at(x).roleValues[y].percent;
counter++;
}
};
};
void printSuperStruct(vector <superStruct> *s)
{
for (int x = 0; x < s->size(); x++)
{
cout << "Count: " << x << endl;
cout << "Name: " << *s->at(x).name << endl;
cout << "Percent: " << *s->at(x).percent << endl;
cout << "pPercent: " << *s->at(x).pPercent << endl;
cout << "Role Name: " << *s->at(x).roleName << endl;
}
};
void sortSuperStruct(vector <superStruct> *s)
{
//runs through list
for (int i = 0; i < s->size(); i++)
{
//checks against lower element
//cout << *s->at(i).pPercent << endl;
for (int j = 1; j < (s->size()-i); j++)
{
//using pointer dereferences messed this up, but, not using them doesn't sort right
if (*s->at(j-1).pPercent < *s->at(j).pPercent)
{
//cout << *s->at(j-1).pPercent << "vs. " << *s->at(j).pPercent << endl;
//I don't think swap is working here
//superStruct temp;
//temp = s->at(j-1);
//s->at(j-1) = s->at(j);
//s->at(j) = temp;
swap(s->at(j-1), s->at(j));
//cout << *s->at(j-1).pPercent << "vs. " << *s->at(j).pPercent << endl;
}
}
}
}
int main()
{
srand (time(NULL));
int numberOfDwarves;
int numberOfRoles;
int maxLabors;
vector <superStruct> allRoles;
vector <Dwarf> myDwarves;
vector <roles> myRoles;
cout << "number of Dwarf's: " << endl;
cin >> numberOfDwarves;
cout << "max labor per dwarf" << endl;
cin >> maxLabors;
cout << "number of Roles: " << endl;
cin >> numberOfRoles;
//this will probably have to be a vector
//Dwarf myDwarfs[numberOfDwarves];
myDwarves.resize(numberOfDwarves);
allRoles.resize(numberOfDwarves*numberOfRoles);
myRoles.resize(numberOfRoles);
//init roles first
for (int x = 0; x < numberOfRoles; x++)
{
myRoles[x].name = x;
myRoles[x].setRolePriorities();
myRoles[x].setNumberToAssign(numberOfDwarves);
}
for (int x = 0; x < numberOfDwarves; x++)
{
myDwarves[x].setRoleValues(numberOfRoles, &myRoles);
myDwarves[x].name = x;
//messy having this here.
myDwarves[x].maxLabor = &maxLabors;
}
initializeSuperStruct(&allRoles, &myDwarves, numberOfRoles);
cout << "Before sort, weighted matrix" << endl;
system("pause");
printSuperStruct(&allRoles);
sortSuperStruct(&allRoles);
system("pause");
cout << "After sort, weighted matrix" << endl;
printSuperStruct(&allRoles);
}
output:
Role Name: 5
Count: 96
Name: 6
Percent: 0.175787
pPercent: 0.0178163
Role Name: 5
Count: 97
Name: 7
Percent: 0.175787
pPercent: 0.0178163
Role Name: 5
Count: 98
Name: 8
Percent: 0.175787
pPercent: 0.0178163
Role Name: 5
Count: 99
Name: 9
Percent: 0.175787
pPercent: 0.0178163
Role Name: 5
srand (time(NULL));
Call that once, at the start of main. Having that in various methods means you'll get a lot of duplicate values.
if (s->at(j-1).pPercent < s->at(j).pPercent)
That indeed compares pointer values, since the pointers don't necessarily point into the same array, with undefined behaviour (will probably compare virtual addresses). If you want to sort by value, you need to dereference
if (*s->at(j-1).pPercent < *s->at(j).pPercent)
And in
for (int j = 1; j < (s->size()-1); j++)
{
//using pointer dereferences messed this up, but, not using them doesn't sort right
if (s->at(j-1).pPercent < s->at(j).pPercent)
you never consider the last element, that should be
for(unsigned int j = 1; j < s->size() - i; ++j)
for a proper bubble sort.
Your bubble sort doesn't seem right to me.
It should resemble this:
void sortSuperStruct(vector <superStruct>& s)
for(int i = 0; i < s.size()-1; i++){
for(int j = i; j < s.size(); j++){
if(*(s[i].pPercent) < *(s[j].pPercent)){
swap(s.at(i),s.at(j));
}
}
}
}
Key differences:
i goes from 0 to size-1, not 0 to size
j goes from i to size, not 1 to size-1
the if statement tests i and j, not j and j-1
the swap also swaps i and j, not j and j-1
Minor differences:
the vector is passed by reference instead of as a pointer. This probably doesn't really matter, but it looks cleaner to me at least.
Note that this will sort from largest to smallest. If you want it smallest to largest, your if statement should have a > sign instead.
I have a problem creating ND arrays dynamically.
So for example:
int **A = 0;
A = new int *[rowsA];
for (int i=0;i<rowsA;i++) {
A[i] = new int[columnsA];
for(int j=0;j<columnsA;j++) {
cout << "Enter " << "(" << i << "," << j << "): ";
cin >> A[i][j];
}
}
And passed to a function like: print_matrix(&A[0][0],rowsA,columnsA);
void print_matrix(int *A, int x, int y) {
for (int i=0;i<x;i++) {
for (int j=0;j<y;j++) {
cout << A[i+j*x] << " ";
}
cout << ",";
}
}
For example:
input : 1,2,3,4,5,6,7,8,9
output: 6-digitnumber 6-digitnumber 4,2 6-digitnumber 5,3 6-digitnumber 6
any ideas?
If by a ND array you mean an Iliffe vector, you aren't building it correctly. The data has to be allocated consecutively and thus in one allocation as the memory returned by successive calls to new isn't necessarily consecutive. This should do the work:
int **A = new int *[rowsA];
int *data = new int[rowsA*columnsA];
for (int i=0;i<rowsA;i++) {
A[i] = data + i*columnsA;
for(int j=0;j<columnsA;j++) {
cout << "Enter " << "(" << i << "," << j << "): ";
cin >> A[i][j];
}
}
Your A variable is an array of pointers (and each pointer points to a sequence of int's) - print_matrix expects a pointer directly to a sequence of int's. The two types are not compatible.
You'll need to either make print_matrix take an int **, or change the use of your A variable to be A[i+j*x] rather than A[i][j]