I want to use designated initializers, but what about the others index that aren't initialized?
Are they spend my memory too?
for example:
EDIT PART: {
int array[590] = 开发者_运维知识库{[2] = 1};
note: I don't use the other array index, like this example i want to use only one, but i will allocate memory for another index?
(okey I know that this example is vague, i don't want only one int or any other type, I don't know how to explain what I want. But I think that explain it is not necessary because my question is not 'how to accomplish this' my question is 'whats happen when I do it?' or 'how it is implemented?', thanks a lot.)
what about the memory in this? I waste 590 piece of memory, or only one? If the first is correct, how Can I spend only one?
and if I do this:?
int array [] = { [2] = 1, [590] = 2};
I will allocate 590 piece of memory, or only two?
}
Thanks so much!
Let's ask Mr. Compiler!
#include <stdio.h>
int main( int argc, char ** argv )
{
int array[] = {[2] = 1, [590] = 2};
printf("sizeof(array) is %d bytes\n", sizeof(array));
}
Survey says:
$ gcc initsize.c
$ ./a.out
sizeof(array) is 2364 bytes
Yep! 591 * 4 = 2364.
Here, you've allocated a 591 element integer array on the stack. It has to be allocated; the compiler does not know what you may do with it (pass it to a library function it knows nothing about, for example). You told it the size is 591 elements, and it obeys...
P.S. There are many "sparse matrix" C libraries; just google for "C library sparse matrix". But, for a vector of 591 elements, they are total over-kill. Now, if you have 10,000 of such vectors, that's another story.
Yes, the declaration you use will create an array of 5 elements, and only set one of them to the value '1'. The rest will be uninitialised (I believe).
What you want, I think, is a hash table or some other kind of associative container, which C does not have in it's standard library. You'll either have to write one yourself, or find one that someone else has written.
Yes memory is allocated when you declare an array, even though you dont initialize every element. If you want only one value stored you need a single variable, you can also Allocate memory dinamically but it requires a good knolewdge of pointers and memory allocation/management functions (malloc,realloc,free,etc.)
精彩评论