Sunday, 17 July 2016

How to create an array without declaring the size in C?



I'm pretty new to new C and I wasn't able to find anything related to this (maybe because I'm not really sure what I'm looking for).



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).



I'm pretty sure that this is possible but I don't know how.



Thanks!


Answer




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:




  • as a global variable with extern class storage (the array is defined elsewhere),

  • as a function parameter: int main(int argc, char *argv[]). In this case the size specified for the leftmost dimension is ignored anyway.

  • as the last member of a struct. This is a C99 extension called a flexible array.



The compiler has no information on the actual size of these arrays. The programmer with 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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...