• C

dynamic array

How to create a dynamic array, with the array size is determine by user input?
Pls give a simple example.Thanx you.
exiangAsked:
Who is Participating?
 
ozoConnect With a Mentor Commented:
#include <stdio.h>
main(){
    int arraysize;
    int *array;
    int i;
    scanf("%d",&arraysize);
    array = (int *)malloc(sizeof(*array)*arraysize);
    for( i=0; i<arraysize; i++ ){
          scanf("%d",&array[i]);
    }
    for( i=0; i<arraysize; i++ ){
          printf("%d\n",array[i]);
    }
}
0
 
cincin77Commented:
int he malloc line;
instead of using sizeof(* array) you should use sizeof(int)
as the elements of the array are integers. However for this specifiz example, sizeof(* array) should be equal to 4 which is equal to sizeo(int) :))

regards...
0
 
TherilCommented:
> instead of using sizeof(* array) you should use sizeof(int)
as the elements of the array are integers. However for this specifiz example, sizeof(* array) should be equal to 4 which is equal to sizeo(int) :))

No, *array points to an int, so the effect is exactly same as sizeof(int). You propably mixed it with sizeof(array)?
Using *array insteads of *int is propably wiser, as there may come situation where one changes the datatype of array.
0
Improve Your Query Performance Tuning

In this FREE six-day email course, you'll learn from Janis Griffin, Database Performance Evangelist. She'll teach 12 steps that you can use to optimize your queries as much as possible and see measurable results in your work. Get started today!

 
cincin77Commented:
array itself is a pointer and * array is a pointer to a pointer whose size is machine dependent.

do i miss something?
0
 
TherilCommented:
> array itself is a pointer and * array is a pointer to a pointer whose size is machine dependent.

Maybe I said "*array points to an int" a bit wrong. What I ment was "*array is an int". Elements of int array are ints and *array is first element of the array (array[0]), so it's size is sizeof(int).

Try this one:

#include <stdio.h>
int main()
{
     char *foo = "foo";
     printf("Sizes: foo: %i *foo: %i\n", sizeof(foo), sizeof(*foo));
}
0
 
cincin77Commented:
iygggg
what i said was really ridiculous, i wrote as if array is a type.
sorry for this mistake.

thanks theril...

0
 
jonninCommented:
note that you can resize the array with realloc; this is slow (do not add one element at a time, add 100 or 1000 or something each time you run out of space)

0
 
exiangAuthor Commented:
should include a header file called <alloc.h>
0
 
ozoCommented:
<alloc.h> is not ANSI standard
should include a header file called <stdlib.h>
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.