Creating a Dynamic Array Function

Started by
5 comments, last by shadowstep00 10 years, 4 months ago

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.

Failure is not an option...

Advertisement

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.

Failure is not an option...

Do you mean this seriously?
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.

#include <stdio.h>
#include <stdlib.h>
int create_array(int N);
int main()
{
int *a,N,i;
scanf("%d",&N);
a = create_array(N);
for (i = 0; i<N; i++)
{
scanf("%d",&a);
}
return 0;
}
int create_array(int N)
{
return (int*)malloc(N*sizeof(int));
}


Program runs ok. But I get these 2 warning
In function 'main':
assignment makes pointer from integer without a cast [enabled by default]
In function 'create_array':
return makes integer from pointer without a cast [enabled by default]

Failure is not an option...

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.

Thanks for your help. :D

Just got to dynamic arrays and did not yet anything about pointer functions.

Problem Solved.

Failure is not an option...

This topic is closed to new replies.

Advertisement