Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping a fixed size array without defining its size in C

Tags:

c

loops

Some example code to start the question:

 #define FOO_COUNT 5

 static const char *foo[] = {
       "123",
       "456",
       "789",
       "987",
       "654"
 };

The way this would normally be iterated over, as for one example, is the following:

int i = FOO_COUNT;
while (--i >= 0) {
 printf("%s\n", foo[i]);

Is there anyway to do the above without explicitly having the human count the number 5? In the future I might add/remove elements and forget to update the size of the array, thus breaking my app.

like image 515
randombits Avatar asked Dec 28 '09 13:12

randombits


People also ask

Can you declare an array without assigning the size of an array?

Answer: No. It is not possible to declare an array without specifying the size. If at all you want to do that, then you can use ArrayList which is dynamic in nature.

How can I get array elements without knowing the size in C?

int reqArraySize; printf("Enter the array size: "); scanf("%d", &reqArraySize); After this you may proceed with this interger input array size : for(i=0;i<reqArraySize;i++) scanf("%d",&arr[i]); Hope this helps you.

Can we define array without size in C?

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

How do you declare an array of unknown size?

int[] integers; int j = 0; do { integers = new int[j + 1]; integers[j] = in. nextInt(); j++; } while((integers[j-1] >= 1) ||(integers[j-1]) <= 100); java.


1 Answers

int i = sizeof(foo)/sizeof(foo[0]);
like image 99
aJ. Avatar answered Sep 27 '22 20:09

aJ.