Is there any way I could find how much bytes are allocated for RandomArray
in this code
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *RandomArray;
int n;
srand(time(NULL));
RandomArray=malloc(sizeof *RandomArray * (rand()%11));
printf("%d %d",sizeof(RandomArray),sizeof(*RandomArray));
return 0;
}
Also I don't know whether above code will ever have any kind of practical usage. But I am looking from programming perspective.
Yes, by saving the size in a variable:
int main()
{
int *RandomArray;
int n;
srand(time(NULL));
size_t size = rand() % 11;
if(size == 0)
{
fprintf(stderr, "Size 0, no point in allocating memory\n");
return 1;
}
RandomArray = malloc(size * sizeof *RandomArray)
if(RandomArray == NULL)
{
fprintf(stderr, "no memory left\n");
return 1;
}
printf("%zu %zu\n", sizeof(RandomArray), size);
// don't forget to free the memory
free(RandomArray);
return 0;
}
Note that sizeof(RandomArray)
returns you the size that a pointer to int
needs to be stored in memory, and sizeof(*RandomArray)
returns you the size of
an int
.
Also don't forget to free the memory.
Ah this is experimental code. Interesting things are there.
N
integers where N
is between 0
to 10
including 0
and 10
.Then you applied sizeof
to the pointer (int*
) and what it points to (int
). It won't matter how much memory you allocate. The output from this line will be same.
There is no error check here. if it was you couldn't tell whether it is successful entirely surely because rand()
may give 0
as result. You need to store it somewhere and check whether it is 0
because on that case malloc
may or may not return NULL
.
Printing what sizeof
returns should be done using %zu
format specifier. It returns size_t
.
- To be more clear remember it is a pointer pointing to dynamically allocated memory.
RandomArray
is not an array - it is an pointer pointing to contiguous memory. That doesn't make it array. It is still a pointer. And thesizeof
trick that you wanted to apply thinkingRandomArray
is an array won't work. In general we keep track of it - using some variable. But here you don't know how much memory you allocated.
malloc
may return NULL
when you pass 0
to it. Handle that case separately. In case you get sz!=0
and get NULL
in RandomArray
throw error.
size_t sz = rand()%11;
RandomArray = malloc(sz);
if(!RandomArray && sz){
perror("malloc");
exit(EXIT_FAILURE);
}
After all this talk - the short answer is, with this setup there is no use of the code (code you have written) so far. You don't know what rand()
returned on that case inside malloc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With