I am trying to do the pointers, the problem was simple wanted me to allocate dynamically an array in a function which will return a pointer to array,
I think i have correct function and program calling it, but i have an error,
can someone help me out please.. thanks, below is my code:
/*
* dyarrya.cpp
*
* Created on: Jan 22, 2014
* Author: BK
*/
#include<iostream>
#include<iomanip>
#include<cstdlib>
#include<string>
i understand that arrayptr is in type and i am attempting to pass pointer variable, what should i do to do what make this function return a pointer to array, i am confused in the terminology i guess
A pointer to an array is really just a pointer to the first element in the array. So if you're using an int array, then the type is a pointer to an int.
Also, the array inside of "arrayptr()" has to be static for this to work properly.
I don't see why. The OP is dynamically allocating the memory for the array on the heap. That means that it will persist after the function returns, and so the pointer is still pointing to valid memory.
i know i am missing two thing from the program
1. delete statement to delete the dynamic allocation.
2. return statement which is the requirement of the question.
@ MikeyBoy: It looks like you're right, I guess it's just a force of habit for me to do this when ever returning a pointer from a function.
To follow on from this - do you understand what making something "static" inside a function actually does? Do you understand the implications if you call the function more than once?
Unless you specifically want static behaviour, using static locals simply to allow the returning of pointers to arrays strikes me as dangerous, probably leading to unexpected and undesired behaviour.
If my intention was to call the function more then once then my preferred method is to pass the array into the function, not to return one from it. That's a design consideration.
EDIT: To be honest, I can't remember the last time I actually returned a pointer from a function I wrote, a few API's do this so I work with pointers that they return to me but that's not quite the same. It just seems backwards in most cases.
Thank every one, this is my corrected code for the fucntion, I jjust made it a pointer return type function..
Thank again
int* arrayptr(int size)
{
int *array;
array = new int [size];
for(int i=0; i<size; i++)
{
cout<<"enter value number "<<i+1<<" : ";
cin>>array[size];
}