const int arr_List[]={34,12,67,34};
but t I have to also declare its size explicitly.
const int size=4;
Now problem is that every-time I run my program with new contents in
arr_List, I have to also change value of size..
Is there any other way for it?
const int size=sizeof(arr_List)/sizeof(arr_List[0]);
--
bartc
const int size = sizeof arr_List / sizeof arr_List[0];
You might want to wrap this in a macro:
#define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr)[0])
...
const int size = ARRAY_SIZE(arr_List);
--
Keith Thompson (The_Other_Keith) ks...@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
<pedantry>
These should be const size_t
</pedantry>
--
Ian Collins
> If I want to initialize a list of numbers to be used in a program.
> like
>
> const int arr_List[]={34,12,67,34};
>
> but t I have to also declare its size explicitly.
> const int size=4;
why? Could you use the ARRAY_SIZE macro suggested by other posters?
int *l = makelist(list, &N);
int *makelist(const char *initialisers, int *N)
{
/* a bit of logic here to call malloc(), and atoi() to convert your list
*/
}
it's a bit of a round about way of doing it, but if it's a nuisance to keep
updating a lot of lists each time, it might be worth the effort.
Huh?
Several of us have already posted a much simpler solution to the OP's
problem: sizeof arr_List / sizeof arr_List[0]. What advantage does
your solution have over that?
I can't see why one would go to that effort when there are the simpler
methods using sizeof.
--
Flash Gordon
Not true. Here's your method again:
| char *list = "34, 12, 67, 34";
|
| int *l = makelist(list, &N);
|
| int *makelist(const char *initialisers, int *N)
| {
| /* a bit of logic here to call malloc(), and atoi() to convert
| your list */
| }
Creating the array gives you a pointer to the first element of
the array and the length of the array. Given just the pointer,
there's still no way to determine the length of the array unless
you explicitly pass the length along with the pointer.
Unless you're talking about reconstructing the int array from the
string every time you use it. You're using a character string
to represent an int array, just for the sake of getting the '\0'
sentinal value.
Or:
int arr_List[] = { 34, 12, 67, 34 };
const size_t arr_List_size = sizeof arr_List / sizeof arr_List[0];
Again, you have a pointer to the first element of the array (the
result of evaluating the array expression ``arr_List'', and a
declared constant holding the length of the array. Use program logic,
perhaps a struct, to keep them associated with each other.
The only things your method gains are obfuscation and inefficiency.