In this problem, I have to create a dynamic array and get data from the user, If the user keep entering value, a new array should be created and the data of the old array should be added to new array. and the old array should be deleted. I am not able to print the data from the new array. It is only printing garbage values. can you check where the problem is ?
#include<iostream>
using namespace std;
int main() {
int size = 5;
int* myarrptr = new int[size];
int* newarr = 0;
int count = 0;
int count2 = 0;
int i;
for (i = 0; i <= size; i++) {
if (i == size) {
count = *((myarrptr + i) - 1);
newarr = new int[size*2];
for (i = 0; i < size; i++) {
*(newarr + i) = *(myarrptr+i);
}
size = size + size;
delete[] myarrptr;
myarrptr = newarr;
*(myarrptr + i) = count;
}
cin >> *(myarrptr + i);
if (*(myarrptr+i) == -1) {
break;
}
count2++;
}
delete[] myarrptr;
cout << newarr[3];
}
Here is the code
I am trying to print the data from the newarr but I am getting garbage values.
This answer is not only for you but for other readers as well.
It looks like you are learning C++ from an outdated source, look at cppreference for examples. Get a recent C++ book or have a go at https://www.learncpp.com/ (that's pretty decent, and pretty up-to-date)
Example of what you want to do in current C++
#include <iostream>
#include <vector>
// output of a datatype in C++ is best generalized by overloading the output stream operator <<
// this will make it work with all kind of streams like std::cout, and std::ofstream (files)
std::ostream& operator<<(std::ostream& os, const std::vector<int>& values)
{
bool comma = false;
os << "[";
// range based for loop instead of index based
// this will never run outside the boundaries of your "array"
for (const int value : values)
{
if (comma) os << ", ";
os << value;
comma = true;
}
os << "]";
return os;
}
int main(int argv, char** argc)
{
std::size_t size;
std::cout << "Enter number of numbers : ";
std::cin >> size;
// for dynamically allocatable arrays use std::vector
// current C++ code should almost never need new/delete and raw pointers
std::vector<int> values(size); // your dynamic memory allocation happens here
// loop over all values by reference so you can modify them
for (int& value : values)
{
std::cout << "Enter a number : ";
std::cin >> value;
}
std::cout << values;
return 0;
}
There a solution already implemented in the standard template library in the vector header file. I would only use raw arrays in game development or constrained environments or to ethically hack. Look at the code I implemented for you. Also, I implemented a sentinel question to exit or continue because if you use a -1 as sentinel, you will not be able to add -1 as a value to display.
#include <iostream>
#include <vector>
int main() {
std::cout << "Enter values to display:" << std::endl;
bool shouldExit = false;
std::vector<int> values = std::vector<int>(0);
do {
std::cout << "Continue? (y/n): ";
char characterInput = '\0';
std::cin >> characterInput;
switch (characterInput) {
case 'y':
case 'Y':
break;
case 'n':
case 'N':
shouldExit = true;
break;
default:
std::cout << "Error: Enter valid input: \'y\' or \'n\' (case insensitive)" << std::endl;
continue;
}
std::cout << "Enter integer value: ";
int value = 0;
std::cin >> value;
values.push_back(value);
} while (!shouldExit);
if (values.size() == 0) {
std::cout << "No values to print" << std::endl;
}
else {
std::cout << "Values: " << std::endl;
for (unsigned int i = 0; i < values.size(); i++)
std::cout << "[" << i << "] = " << values[i] << std::endl;
}
}
If you need the raw array from a vector, you can always use the data() function.
your only printing the 4th value in the array with cout << newarr[3]; you'll need to add a for loop to print all the values
Related
I have code to look for permutations which takes input from the user until the user is satisfied with the amount of input added.
However, when receiving more than 4x input, the code suddenly stuck/terminated itself. I've tried changing the array type to dynamic memory, but the result continues to be the same.
Strangely when I test this code using http://cpp.sh/, it runs normally. I think the problem is with my compiler (I used VS code and MinGW to compile and run it.) What do you think is wrong?
My code is below:
#include <iostream>
#include <string>
using namespace std;
int main() {
int KombAngka;
bool Lanjut = true;
int x = 0;
int *Angka = new int(x);
string YaTidak;
while(Lanjut) {
cout << "Number-" << x + 1 << ": ";
cin >> Angka[x];
LoopYaTidak:
cout << "Are the numbers enough?(y/n)?: ";
cin >> YaTidak;
if (YaTidak == "y") {
Lanjut = false;
}
else if (YaTidak == "n") {
Lanjut = true;
}
else {
cout << "Enter the correct answer!(y/n)" << endl;
goto LoopYaTidak;
}
x++;
}
cout << "All numbers: (";
for (int z = 0; z <= x - 2; z++) {
cout << Angka[z] << ", ";
}
cout << Angka[x - 1] << ")" << endl;
cout << "The number of combinations of numbers used: ";
cin >> KombAngka;
int JumlahAngka = x;
const int StopLoop = JumlahAngka - KombAngka;
for (int i = JumlahAngka - 1; i > StopLoop; i--) {
JumlahAngka = JumlahAngka * i;
}
cout << "The number of queue numbers consisting of " << KombAngka << " different numbers are " << JumlahAngka << endl;
system("pause");
return 0;
}
This line
int *Angka = new int(x);
creates an integer on the heap with a value held by x which here it is 0.
You are accessing memory which you should not, and as mentioned by #fredrik it may cause a buffer overflow.
If you want to create an array on the heap you should do
int *Angka = new int[x];
This creates an array (on heap) of size x.
But since you are using c++ it's better to use vectors, you can simply create a vector with
std::vector<int> Angka;
Vector will take care of memory allocation and all other stuff that you would have to handle if you were to create an array with new.
int grades[100];
int j = 0;
int len = sizeof(grades)/sizeof(grades[0]);
while (j < len)
{
cout << grades[j] << endl;
j++;
}
I have entered only 5 grades and I want to print only that entered grades then ho can I print that?
I have tried to use length of array but since I have created array of size 100, it is printing all unwanted characters at the end.
I have also used '\0' to get end of array but it is not working.
#include <vector>
std::vector<int> grades;
// add 3 grades
grades.push_back(4);
grades.push_back(1);
grades.push_back(9);
// https://www.cplusplus.com/reference/vector/vector/size/
auto size = grades.size();
Just keep track of the size when you read the numbers:
#include <iostream>
int main()
{
int const max_len = 100;
int arr[max_len];
std::cout << "Enter numbers: ";
int len = 0;
while (len < max_len && std::cin >> arr[len]) {
++len;
}
// you've read `len` numbers.
std::cout << "You've entered " << len << " numbers\n";
for (int i = 0; i != len; ++i) {
std::cout << arr[i] << '\n';
}
}
Your code returns the total number of elements the array can store.
Try this instead:-
#include <iostream>
int main()
{
int sample[10];
int length = 0;
for (int integer : sample)
{
if (integer != NULL)
{
length++;
// If you want to print the element as well -
std::cout << integer << std::endl;
}
}
}
Essentially what it does goes through all of the elements of the array and adds 1 to length if that element is not NULL (NULL means a null pointer, or if you're a beginner, just know it means basically nothing).
You can easily change int to any other type.
Hope it helps :)
I am trying to make functions to call in the main function, trying to keep "main" as clean as possible.
so I made a function to get the size array from the user then the user enters the elements of the function, but I got stuck at the linear search function, so want help "Still absolute beginner"
#include <iostream>
using namespace std;
int* Array_Elements () {
static int arr [5] {}, i, size;
cout << "Enter Array size: ";
cin >> size;
cout << "Enter Array Elements: " << endl;
for (i=0; i<size; i++) {
cin >> arr[i];
}
return arr;
}
void Array_Search (int arr [], int n) {
int temp = -1;
for (int i = 0; i < 5; i++) {
if (arr [i] == n) {
cout << "Element found at position: " << i + 1 << endl;
temp = 0;
break;
}
}
if (temp == -1) {
cout << "No Element Found" << endl;
}
}
int num () {
cout << "Please enter an element to search" << endl;
int num;
cin >> num;
return num;
}
int main () {
Array_Search (Array_Elements(), num());
return 0;
}
... trying to keep "main" as clean as possible.
Ok, thats a good motivation. Frankly, I find your main rather confusing. You try to do 3 seperate steps in one line and probably tripped over unspecified evalutation order of the function parameters. I have to admit, I don't remember if or in what version of C++ the order of evaluation of function parameters is specified. And I suggest you to not even try to remember it. Instead write code that does seperate steps in seperate steps.
Your main could look like this:
int main() {
auto arr = Array_Elements();
int number = num();
Array_Search(arr,number);
}
Even without a definition of Array_Elements(), num() or Array_Searcher one can get a rough idea of the three steps made here.
Next, global state is not clean. Your Array_Elements () cannot reasonably be called twice:
int* first_array = Array_Element();
int* second_array = Array_Element();
Both pointers would point to the same arr. The second call to Array_Element will overwrite what the first call assigned.
static int arr [5] {} as workaround to passing arrays around is a hack. It isn't the right way to solve that problem. Sloppy speaking it isn't any cleaner than a sphagetti main.
Use std::array when you want a stack allocated array with size known at compile time and std::vector for dynamic arrays. They can be passed between functions and you need not keep track of the size seperate from the array:
std::vector<int> Array_Elements() {
std::cout << "Enter Array size: ";
unsigned size = 0;
std::cin >> size;
std::vector<int> result(size);
std::cout << "Enter Array Elements: \n";
for (auto& element : result){
std::cin >> element;
}
return result;
}
The loop is a range based for-loop. In a nutshell, it iterates all elements in result and element is a reference to the elements.
Get acustomed to standard algorithms. They aren't doing something that you could not write yourself. Though, they help to write cleaner code, because instead of having several lines of code that all deal with one thing, "find an element", we can have one function call with a meaningful name: std::find.
void Array_Search(const std::vector<int>& arr,int n){
auto it = std::find(arr.begin(),arr.end(),n);
if (it == arr.end()) {
std::cout << "No Element Found\n";
} else {
std::cout << "Element found at position: " << (it - arr.begin()) << "\n";
}
}
In case the element was not found it returns the end iterator. When it does find the element we can calculate the index from an iterator by subtracting the begin iterator.
Live Demo
Lets jump right in, my suggestion to keep the main as clean as possible is to use a class then instantiate its object then use the object to call class methods in the main. This is best practice.
Your code confuses the compiler, in that the function num() precedes the function Array_Elements() in terms of order of evaluation. And I believe you want it the other way around.
Here's how to fix it: Remove the function num(), and make the following changes to your code
int* Array_Elements(int size) {
int* arr, i;
cout << "Enter Array Elements: " << endl;
arr = new int[size];
for (i=0; i<size; i++) {
cin >> arr[i];
}
return arr;
}
void Array_Search (int *arr, int size) {
int temp = -1, num;
cout << "Please enter an element to search" << endl;
cin >> num;
for (int i = 0; i < size; i++) {
if (arr [i] == num) {
cout << "Element found at position: " << i + 1 << endl;
temp = 0;
delete [] arr;
break;
}
}
if (temp == -1) {
cout << "No Element Found" << endl;
}
}
int main () {
int size;
cout << "Enter Array size: ";
cin >> size;
Array_Search(Array_Elements(size),size);
return 0;
}
I have this code of a dynamic array that I turned in as a lab. My instructor responded saying "wouldn't even compile, no resize of the array". I am having trouble dealing with the comment of "no resize of the array", meaning I have to add the ability to resize the array. Please help quick! (It does compile). Appreciate it.
I am supposed to make a program that asks the user to initially size the array. Create an array based on that size asking for a number, and insert the number. Then repeat getting and inserting a number, resizing the array as needed or until they enter -1 for the number.
Print the list.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int count;
cout << "How many values do you want to store in your array?" << endl;
cin >> count;
int* DynamicArray;
DynamicArray = new int[count];
for (int i = 0; i < count; i++) {
cout << "Please input Values: " << endl;
cin >> DynamicArray[i];
{
if (DynamicArray[i] == -1) {
delete[] DynamicArray;
cout << "The program has ended" << endl;
exit(0);
}
else {
cout << endl;
}
}
}
for (int k = 0; k < count; k++) {
cout << DynamicArray[k] << endl;
}
delete[] DynamicArray;
return 0;
}
When the array is full, we need to resize it. Here is my solution
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
int main()
{
int count;
cout << "How many values do you want to store in your array?" << endl;
cin >> count;
if (count <= 0) {
cout << "The value should be greater than zero" << endl;
exit(0);
}
int* DynamicArray;
DynamicArray = new int[count];
int i = 0, value = 0;
while (1) {
cout << "Please input Values: " << endl;
cin >> value;
if (value == -1) {
cout << "The program has ended" << endl;
break;
}
else if (i < count)
{
DynamicArray[i++] = value;
}
else
{
// resize the array with double the old one
count = count * 2;
int *newArray = new int[count];
memcpy(newArray, DynamicArray, count * sizeof(int));
delete[]DynamicArray;
newArray[i++] = value;
DynamicArray = newArray;
}
}
for (int k = 0; k < i; k++) {
cout << DynamicArray[k] << endl;
}
delete[] DynamicArray;
return 0;
}
I have to dynamically allocate an array and pass it to a function to calculate odds of a weighted die being rolled. Whenever I run through my code the function doesn't remember the values added to my array and returns random values, what's wrong about the way I'm passing *weight into the roll function? I added print statements after adding weights in and the weight is entered fine up until it's passed to the function via pointer.
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int roll (int sides, double *weight) {
int total[sides + 1];
total[0] = 0;
for (int i = 1; i <= sides; i++) {
total[i] = total[i - 1] + weight[i];
}
int current = (rand() % total[sides + 1] - 1 + 1);
//cout << current << " ";
for (int i = 1; i <= sides; i++) { // 1 to weight 1,,,,, weight 1 to weight
2
if (current <= total [i] && current > total[i - 1]) {
current = i;
}
}
return current;
}
Function that is supposed to retrieve the random number rolled. ^
int main () {
int sides = 0;
int rolls = 0;
int answer = 0;
int currentRoll = 0;
bool done = false;
double* weight;
double totalWeight;
srand(time(NULL));
cout << "Dice Roll Menu: " << endl << "1. Specify an output file" << endl <<
"2. Enter sides and weight for a die" << endl << "3. Simulate a specified
number of rolls of the weighted die" << endl << "4. Exit" << endl;
while (done != true) {
cout << endl << "Enter a number that corresponds to you choice: ";
cin >> answer;
while (answer == 2) { //SIDES
cout << "Please enter the number of sides on the die (must be
greater than two): ";
cin >> sides;
if (sides < 2) {
cout << "Invalid input, try again." << endl;
}
else {
weight = new double[sides + 1];
for (int i = 0; i < sides + 1; i++) {
weight[i] = 0;
}
break;
}
}
while (answer == 2) {
totalWeight = 0;
for (int i = 1; i <= sides; i++) { //WEIGHT
cout << "Enter a weight for side " << i << ": ";
cin >> weight[i];
cout << "TEST: " << weight[i] << endl;
totalWeight = weight[i] + totalWeight;
if (weight[i] < 0) {
cout << "Invalid input. Try again.";
totalWeight -= weight[i];
i--;
}
}
break;
}
Loop that determines sides and weight and dynamically allocates the array. ^
while (answer == 3) {
cout << "Enter the amount of rolls you would like to perform: ";
cin >> rolls;
if (rolls < 0) {
cout << "Invalid input. Try again.";
}
else {
else if (totalWeight == 0) {
cout << "Please enter weights of the dice first!" << endl;
answer = 1;
}
else {
done = true;
break;
}
}
}
//ACTUAL CODE HERE
for (int i = 1; i <= rolls; i++) { //CALCULATES
currentRoll = roll(sides, &weight[i]);
cout << currentRoll << " ";
}
}
Perhaps many of the misunderstandings that dominate the comments have to do with simply using C++ (and yet without using std::containers).
My out-of-the-box idea (or just plain crazy) is that there really is no conflict between:
"I have to be able to complete this program using 'dynamically allocated arrays', sadly I am not allowed to use vectors
yet all concerned seemed to agree that this is a C++ class assignment.
So, we need think of a way to create an array dynamically (I consider this part easy, not sure why). We want something with compile time fixed size. The array must exist in dynamic memory. (And no std containers.)
The goal has also been stated more simply
I have to dynamically allocate an array and pass it to a function to
calculate odds of a ...
I propose the following. (This code compiles and runs. )
#include <iostream>
using std::cout, std::flush, std::endl;
// Step 1 - wrap an array inside a class
class Array_t
{
const int m_sz;
int64_t* m_arr;
public:
Array_t()
: m_sz(128)
, m_arr (new int64_t[m_sz]) // allocate array in dynamic memory
{
// init for easy sum ... -------------v
for (int j=0; j<m_sz; j+=1) m_arr[j] = 1; // easy sum
}
~Array_t() = default;
int64_t sum() {
int64_t retVal = 0;
for (int i=0; i<m_sz; i+=1)
retVal += m_arr[i]; // direct access to the data!
return retVal;
}
};
// If your C++ 'Hello World' has no class ... why bother?
// Step 2 - auto var the above
class DUMY999_t
{
public:
DUMY999_t() = default;
~DUMY999_t() = default;
int operator()(int argc, char* argv[]) { return exec(argc, argv); }
private:
int exec(int , char** )
{
// here is the array wrapped in a class, an automatic var!
// the array is dynamically allocated in the class (see ctor)
Array_t arr;
// ctor provides the compile time constant
// Step 3
// pass the array (in the class) to some function foo()
cout << "\n foo(arr) :" << foo(arr) << endl;
// Step 4 - can we solve the 'how pass' question?
// It should be obvious that foo is redundant ...
// the following is both more direct
// and object-oriented (a good thing)
// >>> put the function in the object that has the data <<<
cout << "\n arr.sum() :" << arr.sum() << endl;
// invoke an object method which has
// direct access to the data!
return 0;
}
// why pass the data to the function? (c-style?)
int64_t foo(Array_t& arr)
{
return arr.sum();
}
// why not install the function into the object? (c++?)
}; // class DUMY999_t
int main(int argc, char* argv[]) { return DUMY999_t()(argc, argv); }
Typical output:
foo(arr) :128
arr.sum() :128