I want to make a function in C that reads an integer N from the user and then creates a dynamic array with N integer positions.
I had problems with my parameters when I tried. Specifically the array parameters.
This is how I create the dynamic array without creating the function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *array,N,i;
scanf("%d",&N);
array = (int*)malloc(N*sizeof(int));
for (i = 0; i<N; i++)
{
scanf("%d",&array);
}
return 0;
}
Thanks in advance.
Creating a Dynamic Array Function
The code looks broadly correct to me, though it lacks error handling. Can you explain the nature of these problems in more detail?
The code I posted has no problem.
I want this code to be modified.
I want to create a function which takes an integer N (given by the user) and returns a dynamic array with N positions.
You need just a new function with one parameter
And the return type of your array in your case a pointer to int.
What is the difficulty?
So..
I just do this then.
Program runs ok. But I get these 2 warning
Your function should return an int pointer, not an int:
int *create_array(int N)
You'll need to change the declaration and definition.
The compiler is warning that you're trying to treat an integer as a pointer and vice versa. You should probably set your compiler to treat warnings as errors if that only generates a warning, it usually indicates a serious mistake.
Also note that the use of capitals is usually reserved for constants.
Finally, you should free() pointers returned from malloc() when you are finished with them. Otherwise, in bigger programs you will be creating memory leaks.