New to C, thanks a lot for help.
Is it possible to define an array in C without either specifying its size or initializing it.
For example, can I prompt a user to enter numbers and store them in an int array ? I won't know how many numbers they will enter beforehand.
The only way I can think of now is to define a max size, which is not an ideal solution...
Well, you can dynamically allocate the size:
Arrays, by definition, are fixed-size memory structures. You want a vector. Since Standard C doesn't define vectors, you could try looking for a library, or hand-rolling your own.
You need to do dynamic allocation: You want a pointer to a memory address of yet-unkown size. Read up on
malloc
andrealloc
.Above given answers are correct but there is one correction, the function malloc() reserve a block of memory of specified size and return a pointer of type void* which can be casted into pointer of any form. Syntax: ptr = (cast-type*) malloc(byte-size)
Perhaps something like this:
This will prompt for numbers and store them in a array, as you asked. It will terminated when passed given a 0.
You create an accessor function
array_push
for adding to your array, you callrealloc
from with this function when you run out space. You double the amount of allocated space each time. At most you'll allocate double the memory you need, at worst you will callrealloc
log n times, where is n is final intended array size.You may also want to check for failure after calling malloc and realloc. I have not done this above.
You can use
malloc
to allocate memory dynamically (i.e. the size is not known until runtime).C is a low level language: you have to manually free up the memory after it's used; if you don't, your program will suffer from memory leaks.
UPDATE
Just read your comment on another answer.
You're asking for an array with a dynamically-changing-size.
Well, C has no language/syntactic facilities to do that; you either have to implement this yourself or use a library that has already implemented it.
See this question: Is there an auto-resizing array/dynamic array implementation for C that comes with glibc?
If you're a beginner, maybe you don't want to deal with
malloc
andfree
yet. So if you're using GCC, you can allocate variable size arrays on the stack, just specifying the size as an expression.For example:
But keep in mind that this is a non standard extension, so you shouldn't count on it if portability matters.