CS106 B Stanford arryay exercise.

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:

ip---->[0][1][2][3][4][5][6][7][8][9]
[


my code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

#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= new int[n];
	
	

	
	cout<<&p;
	

}
Last edited on
Close.

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.
Last edited on
Oh i see.I will try that
Have i done right this time?

I guess so.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
 * 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= new int[n];
	
	//setting values in the array
	
	for(int i=0;i<n;i++){
	
		p[i]=i;
	
	
	}
	
    p2=&p;

	
	return p2;
	

	 // return result;
}
Topic archived. No new replies allowed.