Below are two methods which both work for creating an array, whose size is determined by user input.
I was always under the impression that data structures whose 'size' was determined by the user after compiling had to be created with malloc(). Example one illustarates this.
However, example two shows a much simpler method that does not require malloc().
Example #1: Create and array whose size is decided by a user input. Uses Malloc().
int main() {
int N;
printf( "Number:" );
scanf( "%d", &N );
int *ptr = createArray(N);
for (int i = 0; i < N; i++) {
printf("%d\n", ptr[i]);
}
free(ptr);
return 0;
}
int *createArray(int N) {
int *ptr = malloc(N);
for (int i = 0; i < N; i++) {
ptr[i]=N;
}
return ptr;
}
Example #2: Create and array whose size is decided by a user input. Does NOT use Malloc().
int main() {
int N;
printf( "Number:" );
scanf( "%d", &N );
int arr[N];
for (int i = 0; i < N; i++) {
arr[i] = N;
}
for (int i = 0; i < N; i++) {
printf("%d\n",arr[i] );
}
return 0;
}
My question is, why is malloc() not needed for example 2, even though the program does not know the array size at the time of compiling?