How to fill an entire array with malloc(sizeof(int)) with some value

Asked

Viewed 319 times

2

I have a problem, I have no idea how to fill this vector with some value, for example, I want to fill it all with -1 (start it all with -1). The problem here is that I don’t know exactly how big my vector is.

    typedef struct argumentosThread {   
        int dim, queens, posicoes, total;
        int *posicCertas;               
        int head;                       
    }ArgumentosThread;

There in the middle of the code I initialize it, I put sizeof(int) because I don’t know what will be the size of the vector, it can be very small or so VERY large.

    argumentos->posicCertas = malloc(sizeof(int));
  • 1

    You have to know somehow, there is no miracle. What you did is not create a vector, you are creating a single element, in this case you know the size, it is 1.

  • 1

    Which vector? If you’re talking about argumentos->posicCertas it is started as a pointer to an integer only and not a vector itself

1 answer

1

At the time you allocate this vector using malloc, also store its size in the structure...

And make a loop for to fill as you wish.

argumentos->posicCertas = (int*)malloc(sizeof(int)*n_pos);
argumentos->n_pos = n_pos;

Then only make one by filling the vector.

It is also interesting to make a malloc return casting.

Browser other questions tagged

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