I'm trying to understand pointers in C++ by writing some examples. I tried creating a pointer array and when I was trying to add integers to it does not work properly. I want to add integers from 0 to 9 to pointer array and print it.
int *array;
array = new int[10];
for(int i=0; i<10; i++){
*array[i] = i;
cout<<*array<<endl;
}
The following will do what you've described:
#include <iostream>
int main()
{
int* array = new int[10];
for (int i = 0; i < 10; ++i)
{
array[i] = i;
std::cout << array[i] << std::endl;
}
delete [] array;
return 0;
}
However in modern C++ the idomatic solution would be something like this:
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v;
for (int i = 0; i < 10; ++i)
{
v.push_back(i);
std::cout << v[i] << std::endl;
}
return 0;
}
You allocated memory for 10 integers for pInt but do not allocate any memory for array. Since array doesn't have any memory allocated it can not hold data. One solution is to just use your pInt variable. On that note where you have *array[i] = i; there is no need to dereference with * as having the brackets [] dereference the pointer. So you can replace that line with pInt[i] = i; then if you call cout << *pInt; you would get the first value in the array. You can cout each in a for loop like cout << pInt[i]; One final thing that you may already know but just incase, whenever you use pointers and allocate memory by using new make sure you deallocate that memory when you are done to prevent memory leaks. For this you would do delete[] pInt;
Allocate something in array otherwise how do you expect it to hold something.(unless you point it to some already allocated memory).
Or assign array=pInt and then you can use it to hold values. array[i]=i
An example:
#include <iostream>
using namespace std;
int main()
{
int *a;
// int *b;
// b= new int[10]; we can simply allocate it to 'a' directly
// a = b;
a = new int[10];
for(int i=0;i<5;i++)
a[i]=i;
for(int i=0;i<5;i++)
cout<<a[i];
delete[] a;
return 0;
}
The pointer variable is nothing but address holder. So here a is not
holding anything significant before initializing. But once you
initialize it either by allocating new or assign it to something
similar it just doesn't point to nowhere. And once you do that you
have some chunk of memory which you can access by that pointer which
is what i did here. What if I didn't initialize and tried to use a.
it's Undefined behavior.
Don't use bits/stdc++.h Link. It might help you write small code but it should never be used in development or production level code.
You should declare a variable as
int *array=new int;
try this
int *array=new int;
int *pInt = new int[10];
for(int i=0; i<10; i++){
*array = i;
cout<<*array<<endl;
}
and if you want to display array from 0 to 9
try this
int *array=new int[10];
int *pInt = new int[10];
for(int i=0; i<10; i++){
array[i] = i;
cout<<array[i]<<endl;
}
for Adding of array
try this
int *array=new int;
int *pInt = new int[10];
for(int i=0; i<10; i++){
pInt[i]=i;
cout<<pInt[i]<<endl;
*array=*array+pInt[i];
}
cout<<"Addition ="<<*array;
return 0;
Related
It is code to reverse the values as they entered.When I am running the following code. It is taking 8 inputs only. After that it is not printing anything.
#include <iostream>
using namespace std;
int main() {
int n;
cin>>n;
int *p = new int(sizeof(int)*n);
int q = n;
for(int i=0;i<n;i++)
{
cin>>*p;
p++;
}
for(int j=0;j<n;j++)
{
cout<<*p<<" ";
p--;
}
return 0;
}
You can also try the following answer.
#include <iostream>
using namespace std;
int main() {
int n;
cin>>n;
int *p = (int *)malloc(sizeof(int)*n);
int q = n;
for(int i=0;i<n;i++)
{
cin>>*p;
p++;
}
for(int j=0;j<n;j++)
{
p--;
cout<<*p<<" ";
}
free(p);
return 0;
}
#include <iostream>
using namespace std;
(Not related to the title, but using namespace std is bad practice that can lead to breakage when switching compilers, for example. Better write the std:: prefix when needed, such as std::cin >>.
int main() {
int n;
cin>>n;
int *p = new int(sizeof(int)*n);
The above is allocating a single int object, whose value is sizeof(int)*n, and p points to that integer. You probably mean:
int *p = (int*)malloc(sizeof(int)*n); // bad style
... at the end:
free(p);
But using malloc in C++ is a bad idea, unless you want to go closer to the operating system for educational purposes.
Slightly better is to use new, which besides allocating the objects also calls their constructors (but nothing is constructed for basic types such as int).
int *p = new int[n]; // so-so style
... at the end:
delete [] p;
The above is not the best practice because it requires manual memory management. Instead, it is recommended to use smart pointers or containers whenever possible:
std::vector<int> p(n);
// continue with the code, just like with the pointers
Or allocate the individual elements only when needed.
std::vector<int> p;
p.reserve(n); // this is a minor optimization in this case
// ...
if (int value; std::cin >> value)
// This is how to add elements:
p.push_back(value);
else
std::cin.clear();
This looks ok:
int q = n;
for(int i=0;i<n;i++)
{
cin>>*p;
p++;
}
But this is broken. When the loop starts, p points after the last element. The following *p dereferences a pointer which goes past the last element:
for(int j=0;j<n;j++)
{
cout<<*p<<" ";
p--;
}
Replacing the order of pointer decrement and dereference avoids the crash:
for(int j=0;j<n;j++)
{
p--;
std::cout << *p << " ";
}
Ok, there many issues here:
int *p = new int(sizeof(int)*n);
This memory allocation is wrong. It allocates n times sizeof(int) bytes, so if int is 4 bytes long it will allocates n * 4 integers.
int q = n;
q variable is never used.
for(int i=0;i<n;i++)
{
cin>>*p;
p++;
}
There is no need for pointer arithmetic here. It would be better to access the array in simple p[i] way.
for(int j=0;j<n;j++)
{
cout<<*p<<" ";
p--;
}
Same here...
return 0;
}
You allocated memory, but never deallocate. This will cause memory leaks.
A better, correct version of the program could be:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int * p = new int[n];
for (int i = 0; i < n; ++i)
{
cin >> p[i];
}
for (int i = (n - 1); i >= 0; --i)
{
cout << p[i] << ' ';
}
delete [] p;
return 0;
}
I am studying for an exam I have next week and am having troubles understanding Dynamic memory allocation. I have a question given which I dont know how to answer;
line 4: int *arr = new int[3];
Write a function that includes the line 4 above and returns the size of the memory location occupied by variable arr. Use the signature:
int size_of_variable_star_arr() ;
I assume I should be using both a main.cpp and a function.cpp - the main file should contain the array variables, while the function file should contain the array that returns it.
Not entire sure what to do here though in order to return the size of the memory location.
//Main.cpp
#include <iostream>
using namespace std;
int main(){
//int *arr = new int[3];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
cout << "Array: ";
}
//function.cpp
#include <iostream>
using namespace std;
int size_of_variable_star_arr(){
int *arr = new int[3];
for(int i = 0; i < 4; i++){
cout << arr[i] << " ";
}
return 0;
}
This is a really strange question, but here's the answer anyway:
int size_of_variable_star_arr() {
int *arr = new int[3];
delete [] arr;
return sizeof(arr);
}
Notes:
I added delete [] to undo the (unnecessary) new
It returns the size of variable arr, as stated in the question. Not the size of the memory block which arr points to.
This question already has answers here:
Closed 10 years ago.
The following code is printing garbage values. I am passing an array to a function which adds 5 to every element, but when it returns that array's pointer, the main is showing garbage.
I have tried both indexing and pointers there in main but still same results. How can I fix this?
# include <conio.h>
# include <iostream>
using namespace std;
int * add5ToEveryElement(int arr[], int size)
{
int theArray[5];
for(int i=0; i<size; i++)
{
theArray[i] = arr[i] + 5;
cout<<theArray[i]<<endl;
}
return theArray;
}
void main()
{
const int size = 5;
int noArr[size];
for(int i=0; i<size; i++)
{
noArr[i] = i;
}
int *arr = add5ToEveryElement(noArr, size);
cout<<endl;cout<<endl;
for(int i=0; i<size; i++)
{
cout<<arr[i]<<endl;
}
cout<<endl;cout<<endl;cout<<endl;cout<<endl;
for(int i=0; i<size; i++)
{
cout<<*arr<<endl;
*arr++;
}
getch();
}
theArray is a local array in the function add5ToEveryElement() which you are returning to main(). This is undefined behaviour.
Minimally you can change this line:
int theArray[5];
to:
int *theArray = new int[5];
It'll work fine. Don't forget to delete it later in main(). SInce you modify the original pointer, save it:
int *arr = add5ToEveryElement(noArr, size);
int *org = arr;
// Rest of the code
//Finally
delete[] org;
Returning an array from a function is generally considered bad.
Unless you MUST have a "new" array, I would suggest the typical case in C and C++ is to modify the input array. If the CALLING function wants to have two separate arrays, then it can do so by making it's own copy. Alternatively, you could write your code to have two arrays passed into your function, e.g.
void add5ToEveryElement(int arr[], int arr2[], int size)
{
for(int i=0; i<size; i++)
{
arr2[i] = arr[i] + 5;
cout<<theArray[i]<<endl;
}
}
then your main would call with two array arguments, and if you wish to use the same as input and output it will do that too.
Sure, this isn't exactly the answer to your question, but it gives a "better" solution to your problem.
I generally dislike allocation in functions - especially "hidden" allocation (this function says it's adding 5 to every element, not "allocate array with added 5 to each element". Code should never do surprising things, and allocating memory is a little bit of a surprise if you only asked for adding 5 to each element)
this is the perfect code
# include <conio.h>
# include <iostream>
using namespace std;
int * add5ToEveryElement(int arr[], int size)
{
int *theArray = new int[5];
for(int i=0; i<size; i++)
{
theArray[i] = arr[i] + 5;
cout<<theArray[i]<<endl;
}
return theArray;
}
void main()
{
const int size = 5;
int noArr[size];
for(int i=0; i<size; i++)
{
noArr[i] = i;
}
int *arr = add5ToEveryElement(noArr, size);
int *p = arr;
cout<<endl;cout<<endl;
for(int i=0; i<size; i++)
{
cout<<arr[i]<<endl;
}
cout<<endl;cout<<endl;cout<<endl;cout<<endl;
for(int i=0; i<size; i++)
{
cout<<*arr<<endl;
*arr++;
}
getch();
delete[] p;
}
I've deleted previous dynamic double "a" array and created a new same-named long int array. But code::blocks gives me an error: "a has a previous declaration as double a". Here is the program:
/*Write a C++ program that receives integer n and
creates a dynamic array a of n size
of doubles, then shows a
maximum number in array, then array a is
deleted, then again receives
integer n and creates a dynamic array
a of n size of long int, then shows minimum number
in array.*/
#include<iostream>
using namespace std;
int main(){
double temp;
int *n = new int;
cin >> *n;
double *a = new double[*n];
for (int i=0;i<*n;i++)
cin>>a[i];
for (int i = 0; i<*n; i++){
if (temp<a[i]){
temp=a[i];
}
}
cout << "Max. num in array: " << temp << endl;
delete[] a;
cin >> *n;
long int *a = new long int[*n];
for (int i=0;i<*n;i++)
cin>>a[i];
for (int i = 0; i<*n; i++){
if (temp>a[i]){
temp = a[i];
}
}
cout << "Min. num in array: " << temp << endl;
delete n;
delete []a;
}
You cannot re-define a variable that was previously defined in the same scope. Initially you have
double *a; // a is a pointer to double
then you try
long int *a; // a is a pointer to long int
It doesn't matter that you delete[] a;. The variable a continues to exist, it is of a pointer type. Of course its allocated memory is deleted, but still you cannot re-declare it.
The instructor probably meant
char* a;
a = new char[n*sizeof(double)];
//...
delete[] a;
a = new char[n*sizeof(long int)];
If you don't want a conflict and want to keep the pointer of type double* and long int* respectively, you can put the variable inside a scope, like
{
double *a = new double[n];
// ...
delete[] a;
} // end of scope, `a` ceases to exist
{ // new scope
long int *a = new long int[n];
// ...
delete[] a;
}
You can't redeclare it. As you have freed up the memory space. But consider this, you can again allocate memory to the double array
Check here Here
#include<iostream>
using namespace std;
int main()
{
int *a;
a = new int[3];
for (int i = 0; i < 3; i++)
{
a[i] = i * 2;
cout << a[i] << endl;
}
delete [] a;
a = new int[3];
for (int i = 0; i < 3; i++)
{
a[i] = i * 3;
cout << a[i] << endl;
}
delete [] a;
return 0;
}
variable "a" is declared as double at first in main function, and you can't use "a" for another variable's name in same scope.
I'm trying to create a function that would dynamically allocate an array, sets the values of the elements, and returns the size of the array. The array variable is a pointer that is declared outside the function and passed as a parameter. Here is the code:
#include <cstdlib>
#include <iostream>
using namespace std;
int doArray(int *arr) {
int sz = 10;
arr = (int*) malloc(sizeof(int) * sz);
for (int i=0; i<sz; i++) {
arr[i] = i * 5;
}
return sz;
}
int main(int argc, char *argv[]) {
int *arr = NULL;
int size = doArray(arr);
for (int i=0; i<size; i++) {
cout << arr[i] << endl;
}
return 0;
}
For some reason, the program terminates on the first iteration of the for loop in main()! Am I doing something wrong?
If you want to allocate memory that way you have to use:
int doArray(int*& arr)
else the pointer will only be changed inside the function scope.
You're passing in the array pointer by value; this means that when your doArray function returns, the value in arr in main is still NULL - the assignment inside doArray doesn't change it.
If you want to change the value of arr (which is an int *), you need to pass in either a pointer or a reference to it; hence, your function signature will contain either (int *&arr) or (int **arr). If you pass it in as a ** you'll also have to change the syntax inside the function from using arr to *arr (pointer-dereferencing), and you'll call it like so: doArray(&arr).
Also, in C++ you should really be using new int[sz] instead of malloc.
You need to add an extra level of indirection to doArray. As written it allocates the array properly but it doesn't communicate the pointer value back to the caller correctly. The pointer from malloc is lost once you return.
If you wrote a function to take a float and change the value, passing the changed value back to the caller, it would need to take a pointer: foo(float *f). Similarly, here you want to pass back an int* value to the caller so your function must be declared as doArray(int **arr) with a second asterisk.
int doArray(int **arr) {
int sz = 10;
*arr = (int*) malloc(sizeof(int) * sz);
for (int i=0; i<sz; i++) {
(*arr)[i] = i * 5;
}
return sz;
}
int main(int argc, char *argv[]) {
int *arr = NULL;
int size = doArray(&arr);
for (int i=0; i<size; i++) {
cout << arr[i] << endl;
}
return 0;
}
Notice how it now dereferences *arr inside of doArray, and how the call is now written as doArray(&arr).
The arr variable in your function is a local copy of the arr pointer in the main function, and the original is not updated. You need to pass a pointer-to-pointer or pointer reference (the former will also work in plain c, the later only in c++).
int doArray(int **arr)
or
int doArray(int*& arr)
Change signature to (specific for c++):
int doArray(int *&arr)
so pointer would be changed at exit from doArray.
You need a pointer to a pointer in your doArray() parameter. If you've never done any programming with pointers before, this can be confusing. I find that it can be easier to see the right types if you annotate your code abundantly with typedefs.
You have the right idea that (int*) can be used to represent an array. But if you want to change the value of your variable arr in main(), you need a pointer to that, and so you will end up with (untested code) something like the following
typedef int *IntArray;
int doArray(IntArray *arr) {
int sz = 10;
*arr = (IntArray) malloc(sizeof(int) * sz);
IntArray theArray = *arr;
for (int i=0; i<sz; i++) {
theArray[i] = i * 5;
}
return sz;
}
when calling doArray, you will need to pass the address of your variable (so doArray knows where to write to):
int main(int argc, char *argv[]) {
int *arr = NULL;
int size = doArray(&arr);
for (int i=0; i<size; i++) {
cout << arr[i] << endl;
}
return 0;
}
This should work.
As others have pointed out, you're passing your array (the int *) by value, so when you say arr=... you're not actually changing the array you passed in.
You're also got a memory leak, as you've written it. It's not a big deal when you only call doArray once in the body of your program, but if it gets called repeatedly and the array is never freed (or deleted, if you made it with new) then it can cause problems. Typically the best way to deal with this is by using the STL. You'd then write
#include <vector>
#include <iostream>
int doArray(std::vector<int> &arr) {
int sz = 10;
arr.resize(sz);
for (int i=0; i<sz; i++) {
arr[i] = i * 5;
}
return sz;
}
int main(int argc, char *argv[]) {
std::vector<int> arr;
int size = doArray(arr);
for (int i=0; i<size; i++) {
std::cout << arr[i] << std::endl;
}
return 0;
}
However, with the STL there are more idomatic ways than returning the size, since you can just ask for arr.size(), and if you get really fancy, can use functions like for_each or the ostream_iterator to print all your elements.