Reputation: 31
i have code like this:
int main()
{
double *u;
int len;
u=(double *)malloc(sizeof(double)*10);
len = sizeof(u);
printf("Length Of Array = %d\n", len);
return 0;
}
but the length is 4 Not 10. how can i extract 10 from pointer u?! please help me thank you
Upvotes: 1
Views: 162
Reputation: 2862
A pointer doesn't include information about the size of the memory area. You have to keep track of the size yourself. For instance, you can make a custom type (for example, a struct
) that contains both the pointer and the size of the allocation at the same time.
Here's a simple implementation to get you started:
typedef struct {
double* ptr;
size_t len;
} double_arr_t;
// prototype
double_arr_t alloc_double_arr(size_t len);
int main(void) {
// alloc the new array of 10 `double` elements
double_arr_t arr = alloc_double_arr(10);
printf("Length of 'arr' is %zu\n", arr.len); // Length of 'arr' is 10
// assign a value to the first element
arr.ptr[0] = 3.14;
// get the value of the first element
double first_element = arr.ptr[0];
// free the array when you're done using it
free(arr.ptr);
}
double_arr_t alloc_double_arr(size_t len) {
double_arr_t res;
res.ptr = malloc(len * sizeof(double));
res.len = len;
return res;
}
Upvotes: 1
Reputation: 67476
It is not possible. sizeof
is giving the size of the object. In your case the object is u
which is a pointer. Your system is 32 bits as pointers are 4 bytes.
if you sizeof(*u)- you will get the size of referenced type. In this case it is the double
. It will be 8 bytes long at most systems.
using sizeof
to get the size of the length of the string is one of the most frequent questions asked here.
Upvotes: 2
Reputation: 234635
That's your job. C does not provide a portable way of knowing, given a pointer, how much memory has been allocated.
sizeof
will give you sizeof(double*)
, that's all. That's 4 on your system.
Upvotes: 5