I'm trying to create a int and a float array without a size (it might be 0 or it might increment while the user use the program).
I was trying to do the follow:
int bills[];
float totalAmount[];
I can't assign a max size because I'm printing each array with a for loop (If I assign a size of 99 I'll print 99 lines, and I don't want that).
C does not support arrays with a dynamic number of elements. The number of elements of an array must be determined either at compile time or since C99 can be evaluated at runtime at the point of creation. Once the array is created, its size is fixed and cannot be changed. There are a few cases where the size is not explicitly specified between the []
, either in array definitions or in array declarations.
You can define an array without an explicit size for the leftmost dimension if you provide an initializer. The compiler will infer the size from the initializer:
int a[] = { 1, 2, 3 }; // equivalent to int a[3] = { 1, 2, 3 };
int m[][2] = {{ 1, 2 }, { 3, 4 }}; // equivalent to int m[2][2] = {{ 1, 2 }, { 3, 4 }};
char s[] = "Hello world\n"; // equivalent to char s[13] = "Hello world\n";
Note how the compiler adds the implicit null terminator in the string case.
You can declare an array without a size specifier for the leftmost dimension in multiples cases:
extern
class storage (the array is defined elsewhere),int main(int argc, char *argv[])
. In this case the size specified for the leftmost dimension is ignored anyway.struct
with more than one named member. This is a C99 extension called a flexible array.The compiler has no information on the actual size of these arrays. The programmer will use some other information to determine the length, either from a separate variable or from the array contents.
In the case of a function argument, the array is passed as a pointer and even if the number of elements is specified, sizeof(argv)
evaluates to the size of a pointer.