Cannot do this operation, the pattern you are using is suitable for array, what you’re using is not a array, though it may seem. This is a pointer to an item and you know that there are several of them so you can navigate the following items with the pointer as if it were one array, but it’s not.
The sizeof
is an operator that solves the value there at compile time, it cannot be used for something that will be solved at runtime.
The only way to know the amount of items in this sequence is to adopt a pattern that holds this value or counts how many items you have, if you adopted a terminator in the sequence (is what the string of C makes).
If saving the simplest and most widely used is just keeping a variable with this value, then every API that needs to receive this pointer will have to receive this amount of items together to control access. Other form used is to create a struct
that makes a single object have the size of the sequence and the sequence (this may be a problem in some compilers). You can also use only one #define
global, makes sense in certain codes.
The code can be much better written and make more sense:
#include <stdio.h>
#include <stdlib.h>
#define TAMANHO 10
int main(void) {
int *vetor = malloc(TAMANHO * sizeof(int));
for (int i = 0; i < TAMANHO ; i++) {
vetor[i] = i + 1;
printf("%d\n", vetor[i]);
}
printf("\n%d", TAMANHO);
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).
– Maniero