Next: Function pointers
Up: Pointers
Previous: Allocation
Contents
Index
Pointers also find a valuable place as return types
of subroutines. For instance, the previous example
of dynamically creating an array of a specific size
could be put into a subroutine as follows.
#include <stdio.h>
int *create_array(int);
int main(void) {
int *scores, n, i;
printf("How many scores? ");
scanf("%d", &n);
scores = create_array(n);
for(i=0; i<n; i++) {
printf("scores[%d] = %d\n", i, scores[i]);
}
free(scores);
return 0;
}
int *create_array(int n) {
int i, *p;
p = (int *) malloc(n * sizeof(int));
for(i=0; i<n; i++) {
p[i] = i;
}
return p;
}