Original Instructions: "Write a C function that will input values into an array of type int. Have the array and the number of elements in the array passed as parameters to your function. Use a local pointer variable to traverse the array. "
So this is what I've come up with, was wondering if someone could have a look at it because I wasn't quite clear on the instructions exactly. Maybe if you've dealt with this sort of problem before you can tell me if I'm on the right track, the second part of the problem will be to then write a function that outputs the contents of the array using a function.
Code:
/*
My name is Jack Trocinski
*/
#include <stdio.h>
#include <stdlib.h>
void input(int *ptr, int j);
int main()
{
int j; // number of elements in array
int *ptr; // memory allocation
printf("Please enter the amount of elements you wish to have in the array: ");
scanf("%d", &j);
if (j > 0) {
input (ptr, j);
}
else printf("Sorry, you have entered an invalid number.\n");
system("pause");
return 0;
}
void input(int *ptr, int j) {
int i; // used in for loop
ptr = malloc( j * sizeof(*ptr) );
for ( i = 0; i < j; ++i) {
printf("Input a value to the array and press enter: ");
scanf("%d", &ptr[i]);
}
}
Everything compiles nicely, my problem is strictly did I get the right concept writing this type of code.