I am trying to do this exericse.I am not sure whether i did the exercise according to what the exercise is asking me to do.I think i did what the exercise wants.Could u check it for me please guys?
here is the exercise:
Write a function IndexArray(n) that returns a pointer to a dynamically allocated integer array with n elements, each of which is initialized to its own index. For example, assuming that ip is declared as
int *ip;
the statement
ip = IndexArray(10);
should produce the following memory configuration:
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <stdlib.h>
#include "genlib.h"
#include <simpio.h>
void indexArray(int n);
int main(){
indexArray(10);
}
//a function to return the pointer of the array
void indexArray(int n){
int result=0;
int *p;
p= newint[n];
cout<<&p;
}
You never return the pointer. You allocate it, then as you leave the function, you lose access to it, so it becomes leaked memory. indexArray(int) needs to return a pointer to an int, and you need to assign that address to a variable in main.
Also, you need to set the values of the ints in the array, using a loop.
/**
* File: narcissism.cpp
* --------------------
* This file defines a program that prints out
* the first 25 narcissistic numbers.
*/
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <stdlib.h>
#include "genlib.h"
#include <simpio.h>
int** indexArray(int n);
int main(){
int** pointer=0;
pointer=indexArray(10);
cout<<pointer;
}
//put the double aestriks after int is bcoz it was complaining ""
int** indexArray(int n){
int *p;
int **p2;
p= newint[n];
//setting values in the array
for(int i=0;i<n;i++){
p[i]=i;
}
p2=&p;
return p2;
// return result;
}