+ 4
C++ struct array
Hey, can somebody tell me how it works: I have structure struct tellBook { int phone; }; And I've created 20 new instances of it in array tellBook* book = new tellBook[20]; if I would fill first 5 instances with some numbers, what values of others? I know there will be 0 but why is that? And how can I make loop with WHILE to output all of the filled instances? int i = 0; while( I do not know that to write here ) { cout << book[i].phone; i++; }
5 Réponses
+ 1
When allocating an array with new you need to loop through it by remembering the size. Therefore the while statement needs to be "(i<20)".
Normally you could get the number of elements by dividing the size of 1 element by the size of the whole array (sizeof(book)/sizeof(book[0])), but this doesn't work for arrays constructed via new operator.
Take a look at vectors to store multiple instances of objects. Way easier to handle.
And the reason why the other values are 0 is that unassigned integers get initialized with 0. But you shouldn't use uninitialized values, because some compilers don't set it to 0, but leave it at whatever leftover bits are remaining inside the memory location the variable is using (garbage).
If you have questions just ask.
0
But when I do i < 20 I have output with my values and other - zero
0
And sizeof(book)/sizeof(book[0]) gives 1 though I have 5 elements of array.
I do not know why sizeof(book) gives 4 like sizeof(book[0])