I have dynamically stored memory of a vector in C, does not return the allocated size, why?

Asked

Viewed 48 times

0

This code is an example of another code with the same problem. I dynamically stored the memory, but when I’m printing the vector size with the len, strangely prints 1 and not 10 as expected. The second for prints the 10 values correctly. Why not print 10 len?

int main()

    int *vetor;

    vetor = (int*)malloc(10*(sizeof(int)));

    for(int i=0; i<10 ; i++)
    {
        vetor[i] = i+1;
    }

    for(int j=0; j<10 ; j++)
    {
        printf("%d\n",vetor[j]);
    }

    int len = (int)(sizeof(vetor)/sizeof(vetor[0]));

    printf("\n%d",len); //Len retorna 1 no

    return 1;
}
  • 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).

1 answer

2

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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.