C++ printing array results - c++

I was able to fix some of the errors. Now I am just getting 3.
1. control reaches end of non-void function at } before the
void displayIntegerArray(int *arrayPtr,int arraySize) function.
2. expected expression at delete[];.
3. expected expression at return 0;.
#include <iostream>
#include <iomanip>
using namespace std;
// Function prototypes
void populateIntegerArray(int *arrayPtr, int arraySize);
void displayIntegerArray(int *arrayPtr, int arraySize);
void findMaximumInteger(int *arrayPtr, int arraySize);
//method to populate array
void populateIntegerArray(int *arrayPtr,int arraySize)
{
for(int i=0;i<arraySize;i++)
{
cout<<"Enter value for array element:"<<i<<":";
cin>>arrayPtr[i]; //reading value
}
}
void findMaximumInteger(int *arrayPtr,int arraySize)
{
int maximum = arrayPtr[0];
{
for(int i=0;i<arraySize;i++)
{
if(maximum<arrayPtr[i])maximum=arrayPtr[i];
}
cout<<"Maximum integer in array is: "<<maximum<<endl;
}
}
void displayIntegerArray(int *arrayPtr,int arraySize)
{
for(int i=0;i<arraySize;i++)
{
cout<<&arrayPtr[i]<<": arrayPtr["<<i<<"] = "<<setw(15)<<arrayPtr[i]<<endl;
}
}
int main()
{
int arraySize;
// Read array size
cout<<"Enter desired array size:";
cin>>arraySize;
// Print array
cout<<"arrayPtr = "<<arraySize<<endl;
populateIntegerArray( arrayPtr, arraySize);
displayIntegerArray(arrayPtr, arraySize);
findMaximumInteger( arrayPtr, arraySize);
cout<<"DELETING array at arrayPtr = "<<arrayPtr<<endl;
delete[];
return 0;
}

In main function:
There is undeclared variable; arrayPtr.
So you have to declare it and allocate memory for it dynamically.
int* arrPtr = new int[arraySize];
You also have to provide the delete [] operator the arrayPtr to free the memory allocated.
Finally main function will be like that:
int main()
{
int arraySize;
// Read array size
cout<<"Enter desired array size:";
cin>>arraySize;
int *arrayPtr=new int[arraySize];
// Print array
cout<<"arrayPtr = "<<arraySize<<endl;
populateIntegerArray( arrayPtr, arraySize);
displayIntegerArray(arrayPtr, arraySize);
findMaximumInteger( arrayPtr, arraySize);
cout<<"DELETING array at arrayPtr = "<<arrayPtr<<endl;
delete[] arrayPtr;
return 0;
}

So there are a couple of things that ain't quite right with your program my dude, but they mainly stem from you not creating a arrayPtr in main. If you don't create something to point to a chunk of memory then your program wont know where the array is.
https://www.cplusplus.com/doc/tutorial/pointers/
The next problem is that, because you never created the pointer to the memory, you also forgot to create the space for the memory. If the array was the same size every time your program ran and was reasonably small then you could just allocate the space on the stack. However you don't so you need to allocate the memory dynamically. This means that you need to ask your operating system for the memory and get back its location. This can be done with the new[] operator. Then when you are done using the memory you tell the program to de-allocate it with the delete[] operator. (If you don't then memory will keep being marked as used despite your program ending. This is called a memory leak.)
https://www.cplusplus.com/doc/tutorial/dynamic/
Next you aren't actually displaying the location of the array. You want to print the new arrayPtr variable to see the location.
Lastly your post is a bit hard to work with. The formatting is a bit inconstant and that makes it significantly harder to read. Luckily your program was simple enough that it isn't too time consuming to read through and figure out what is going wrong. However, as your programs get more complex and larger, many people won't be willing to look through your whole program and find your bugs for you. Try to narrow down where you think the error is coming from and post: some context, the relevant chunk of code, and the exact error messages.

Related

Error when trying to print out array in a loop using cout

#include <cstdio>
#include <iostream>
int main (){
int n;
std::cin>>n;
int*a;
for (int i=0;i<n;i++){
std::cin>>a[i];
}
for(int i=0;i<n;i++){
std::cout<<a[i];
}
return 0;
}
I just started working on a problem and I wanted to check if I knew how to read and array and make a sample output array. When I include the second loop program crashes as soon as I enter n and the first number With the following message
3 1
Process returned -1073741819 (0xC0000005) execution time : 4.943 s
Press any key to continue.
int *a; is a pointer to an integer, it is just a pointer to some memory, it has no memory allocated on its own. Since you are dereferencing this pointer a[i] without setting it up first, your compiler should even give you some warning telling that you are using a variable that has not been initialized.
0xC0000005 error code in Windows means access violation. In this case, you are trying to write to some memory which you don't have access to.
You need to allocate memory before you can read or write to it.
If you know beforehand how many entries you will have, you can do static memory allocation, if you don't, then you need to do dynamic memory allocation.
For instance, if you knew that you would need only 20 entries at max, you could easily swap int *a; for int a[20];.
But since you are only getting to know how many entries there will be when the program runs, then you need to go for dynamic memory allocation: int *a = new int[n];.
So your code should be
#include <cstdio>
#include <iostream>
int main (){
int n;
std::cin>>n;
int *a = new int[n];
for (int i=0;i<n;i++){
std::cin>>a[i];
}
for(int i=0;i<n;i++){
std::cout<<a[i];
}
delete[] a; // Release allocated memory.
return 0;
}
You need to allocate memory for a, otherwise the behaviour of the program is undefined. Writing
int* a = new int[n];
would to it, followed by delete[] a; when you're all done (put this just before return 0;).
Alternatively, use a std::vector<int> a(n); and all the memory allocation will be taken care of for you.
Try : int a[20]; rather than int *a;
Your a doesn't point to any valid memory, resulting in undefined behaviour.
What you need is an std::vector :
#include <vector>
int n;
std::cin>>n;
std::vector<int> numbers;
for (int i=0;i<n;i++){
int val;
std::cin>>val;
numbers.push_back(val);
}
for(int i=0;i<n /* or numbers.size()*/ ;i++){
std::cout<< numbers[i];
}
This takes care of dynamic allocation for you so that you don't have to do the dirty stuff yourself.
There are a few issues with your code. Primarily, you request the number 'n' then need to allocate enough space to store that many integers.
The best way to do that is to use vector. You can create this with:
std::vector< int > numbers( n );
You can also create it allocating the memory but waiting until you have data:
std::vector< int > numbers;
numbers.reserve( n );
You also should probably validate your input, for example your input stream (cin) will be invalid if the user enters something that is not an integer, and the original 'n' should be positive if you are going to try to create a vector of that size, and you may need to set a limit or you will suffer a bad_alloc. If you do not mind suffering a bad_alloc you should catch that exception and print an error such as "There is insufficient space to allocate as many numbers".
Of course if you enter a high number like 10 million, you may find the compiler is able to allocate that many but your user will get bored in your loop when you ask him to enter integers 10 million times.
You do not need <cstdio> as a header. You will need <vector> and <iostream>.
int* is a pointer to int, not an array.
To create an array of int, example: int a[100]; - where 100 is the size
Moreover, you should use a std::vector<int> instead:
vector<int> vec;
for (int i = 0; i != n; ++i) {
int temp;
cin >> temp;
vec.emplace_back(temp);
}

Returning a Pointer from a function c++

When I try to compile in C++ it says that there is an undefined reference to sort_Array(int *, int). I have been messing with this for about an hour and I can't figure out why I am getting this error. I thought it was telling me to use a pointer. I have to use the prototype exactly as it is written for the assignment so i can't change the array to a pointer or pass it by reference like I thought it was telling me to. I also have to get the size of the array from the user. Could this be a situation where I need to dynamically allocate the array. It crossed my mind, but I am not sure.
This is the prototype
int *sort_Array(int [], int);
This is how I am trying to use it
int size;
int initial_Array[size];
cout << "What is the size of your array?" << endl;
cin >> size;
cin.ignore();
sort_Array(initial_Array, size);
This is the actual function
int *sort_array(int unsorted_Array[], int size)
{
int *sorted_Array, i;
sorted_Array = new int[size];
//Function for sorting the array.
selection_Sort(unsorted_Array, size);
//Copies the newly sorted unsorted array variable to the sorted array varible.
for(i=0; i<size; i++)
{
unsorted_Array[i] = sorted_Array[i];
}
return sorted_Array;
}
You define intial_Array with an uninitialised size:
int size;
int initial_Array[size];
Which is UB.
But your error comes from calling sort_Array when you've defined sort_array

c++ pointer syntax error

I'm studying for an exam in c++ and i have a question on the past papers
"Write a function in C++ that takes as input an array of doubles and the length of the array, and returns an array twice the length. The first half of the returned array should contain a copy of the contents of the original array. The second half of the returned array should contain the contents of the original array in reverse order."
"The function should have the following prototype: double *copy_and_reverse(double *a, int length);"
since im obviously new to c++ i got stuck in my solution, my code so far is:
double *copy_and_reverse(double *a, int length){
double *b[length*2];
for(int i=0;i<length;i++){
*b[i]=a[i];
}
for(int i=length;i<length*2;i++){
int w=length-1;
*b[i]=a[w];
w--;
}
return *b;
}
int main()
{
double nums[2]={1.23,5.364};
double *pnums=nums;
*pnums=*copy_and_reverse(pnums, 2);
I think i got the core of the method correct but i'm just stuck in the syntax of using pointers, any help is appreciated and if possible a reasoning behind it so i can learn for the exam.
You've got a few problems with this code.
First
double *b[length*2];
Here you're declaring an array of pointers to doubles. The array is of size length * 2, however, none of the pointers in this array are valid yet. This is probably not what you intended to do.
You want an array of doubles, of size length * 2. You can't return an array in C++ but you can return a pointer to some memory that contains an array of doubles.
Let's start by allocating enough memory for all those doubles
double *b= new double[length * 2];
In your first for loop you can treat result as an array
for(int i=0;i<length;i++){
b[i]=a[i];
}
Here you're copying the values from a for each index i to be at the same index. I'll let you figure out how to fill in the reverse part for the second half of the array. You're on the right track, however you might want to think about doing it all in one loop ;)
Your return statement just needs to return your variable b, as it's already a double *.
return b;
An important thing to remember is that you're allocating memory in this function with new. You are responsible for deleting this when you're done with it. Also, when you allocate using new and [] you have to delete using [] as well.
delete [] b;
you can call your function just by de-referencing the first item in your array.
int main() {
double nums[2]={1.23,5.364};
double *pnums = copy_and_reverse(&pnums[0], 2);//don't forget to clean up pnums afterwards!
There are quite many errors in your code. The major one is that you need to allocate new array of doubles. And return that array. I'd suggest compare this with your version line by line:
double *copy_and_reverse(double *a, int length){
double *result = new double[length*2];
for(int i=0;i<length;i++) {
result[i]=a[i];
}
int r = length*2;
for(int i=0; i < length;i++){
result[--r]=a[i];
}
return result;
}
And your main() shall look like:
int main()
{
double nums[2]={1.23,5.364};
double *pnums = copy_and_reverse(nums, 2);
...
delete[] pnums;
}
Ok, there are at least two problems with this:
double *b[length*2];
The first problem is that you are declaring a local array (of pointers), which you will then try to return:
return *b;
(You're returning the wrong thing here, too, but that's another story) You can't return a pointer to a locally-allocated thing because as soon as the function returns, the locally-allocated thing will be destroyed. Instead, given that you must return a pointer to the first element of an array, you have to dynamically allocate that thing using new.
Second, you can't declare an array like this using a length which s only known at runtime. But this problem will be obviated when you use new to dynamically allocate the array.
I would normally say that you shouldn't be doing any of this at all, and just use a std::vector -- but clearly a requirement of this assignment is to use a dynamically allocated C-style array. (Which I take great issue with your professor on.)
I would also say that the prototype:
double *copy_and_reverse(double *a, int length);
doesn't declare a function which takes an array, as your professor incorrectly asserts, but a function which takes a pointer to a double. That that pointer is the first element in an array doesn't magically make a an array. In short: an array and a pointer are not the same thing.
These last two observations are just for your benefit.
I assume this is not your homework and I am trying to help you out.
Look at the comment of code.
double *copy_and_reverse(double *a, int length)
{
double * b = new double[length*2]; //create a new array using new[]
for(int i=0;i<length;i++){
b[i]=a[i]; //addressing element with []
}
int w=length-1; //I assume this is what you want
for(int i=length;i<length*2;i++){
b[i]=a[w];
w--;
}
return b;
}
int main()
{
double nums[2]={1.23,5.364};
double *pnums = copy_and_reverse(nums, 2);
delete[] pnums;
}
Also noted the memory is allocated in the function, so in the main, you want to delete it by using [].

Make array in cpp

I am trying to make a new array in my project
the code is:
#include <iostream>
using namespace std;
void makeArray( int *& arrayPtr, int size );
int main( )
{
int * arrPtr;
int size =10;
makeArray( arrPtr, size );
for(int j=0;j<size;j++)
{
cout<<arrPtr[j]<<endl;
}
}
void makeArray( int *& arrayPtr, int size )
{
int arr[size-1];
for(int i=0;i<size;i++)
{
arr[i]=0;
}
*&arrayPtr=*&arr;
}
According to the requirements i need to use the above "makeArray" method inorder to make the array.
When i run the code the output is garbage values not zero.....
any help will be appreciated
thank you
The way you are creating the array is on the stack, which means that it will not exist after the makeArray function finishes.
You will need to allocate the array on the heap.
So:
int arr[size-1];
should be:
int *arr = new int[size-1];
Also, I think you mean to do this in makeArray():
arrayPtr = arr;
Instead of:
*&arrayPtr=*&arr;
Which compiles but is more complex and is functionally the same thing in this context.
But you may prefer just returning an int* instead of taking a reference to the pointer.
Then when you are done using the array in main(), and set it to NULL just in case you accidentally use it again, like this:
for(int j=0;j<size;j++)
{
cout<<arrPtr[j]<<endl;
}
delete [] arrPtr;
arrPtr = NULL;
Why are you declaring a parameter as 'int *& arrayPtr'? Do you just need a pointer to an array? You should use 'int *arrayPtr' instead.
To answer your question, the problem is that you are declaring an array in the function makeArray's stack. Upon the completion of a function, that function's stack is destroyed, so you're passing the address of junk data. To avoid this, use dynamic memory allocation instead.
EDIT: Also, you should use memset instead of a for loop to zero an array. It's much faster.
The "arr" which you allocate in "makeArray()" is local. and when the functione is over the array is release. When you back to main you get garbage.
What you want to do, is to use the "new" operator to allocate this new array to be used in all program, unless you will free this memory by "delete".
so you can set your makeArray() to:
int* makeArray(int size )
{
int *arr = new[size];
for(int i=0;i<size;i++)
{
arr[i]=0;
}
return arr;
}
the in you main you need to initialize your arry by:
int * arrPtr = makeArray(10);
just don't forget to release this memory after you finsh:
delete[] arrPtr ;

using Pointers to a series of integers in C++

I am trying to make a c++ program with a class which holds integers on the "heap" and has only one method, pop() which returns the first item in the class and removes it. This is my code so far:
#include <iostream>
using namespace std;
class LinkList {
int *values; //pointer to integers stored in linklist
int number; // number of values stored in linklist
public:
LinkList(const int*, int); // Constructor (method declaration)
int pop(); // typically remove item from data structure (method declaration)
};
LinkList::LinkList(const int *v, int n){
number = n;
*values = *v;
int mypointer = 1;
while (mypointer<n) {
*(values+mypointer) = *(v+mypointer);
mypointer++;
}
}
int LinkList::pop() {
if (number>0) {
int returnme = *values; //get the first integer in the linklist
number--;
values++; //move values to next address
return returnme;
}
else {return -1;}
}
int main() {
int test[] = {1,2,3,4,5};
LinkList l1(test,5);
cout << l1.pop() << endl;
LinkList l2(test,5);
cout << l2.pop() << endl;
return 0;
}
The issue is that its failing at the line *values = *v, if i remove the 4th and 5th lines from the main method, I no longer get this issue, so its go to be a memory management thing.
What I want to do is to get values to point to a continuous bit of memory with integers in. I have tried to use arrays for this but keep just getting random memory addresses returned by pop()
Background: normal I programming in java, I've only be using C/C++ for 2 months, I'm using eclipse IDE in ubuntu, I can make very basic use of the debugger but currently I dont have functioning scroll bars in eclipse so I can't do somethings if they dont fit on my screen.
You are dereferencing an uninitialized pointer (values) at the line *values = *v; which is undefined behavior (UB). What this line says is "get the integer that values points to and assign to it the value pointed by v". The problem with this logic is that values doesn't yet point to anything. The result of this UB is the crash that you receive.
There are many other problems with this code, such as passing a const int* to the constructor with the intent of modifying those values. The biggest problem is that this is not an actual linked list.
*values = *v;
You dereference the values pointer in this line before initializing it. This is the source of the later errors, and the non-errors in the first three lines of main are simply due to luck. You have to allocate space via values = new int[n] and deallocate it in the destructor via delete[] values. std::vector does this work in a clean and exception-safe way for you.
Perhaps the problem is that you're incrementing an integer - mypointer, rather than a a pointer. If the integer requires more than one byte of space, then this might lead to errors. Could you try declaring a pointer and incrementing that instead?
The values member variable is a pointer to uninitialized memory. Before you start copying numbers into it you have to point it to valid memory. For example:
LinkList::LinkList(const int *v, int n){
number = n;
values = new int[n]; // allocate memory
int mypointer = 0;
while (mypointer<n) {
*(values+mypointer) = *(v+mypointer);
mypointer++;
}
}
LinkList::~LinkList() {
delete values; // release memory
}
Also, why do you call this a linked list while in fact you are using a memory array to store your numbers?