Find size of array pointed to by pointer [duplicate] - c++

This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
Closed 10 years ago.
I have the below code:
int* d = (int*) malloc(100 * sizeof(int));
cout<<"size of d which is pointer is: " << sizeof(d)<<endl;
I know that sizeof outputs 4 as d is a ptr. But, how can I find the sizeof the entire array using sizeof

You cannot - sizeof is a compile time operation and hence not dynamic.
As you are using c++ use std::vector instead. Otherwise create a structure to store both the pointer and the size of the array. Pass that around instead.

The pointer gives you the place in memory where your data is stored which is why you can't get it's size only from that information.
It's analogous to knowing how big my house is from knowing my address (without prior knowledge or the use of tools like Google Maps)

The direct ans. is no you can't but you can try this :
int x[]={1,2,3,4};
int *ptr=x;
decltype(sizeof(*ptr)) size=0;
while(*ptr<5){
size =size+sizeof(*ptr);
ptr++;
}
cout<<"Size is : "<<size;
Output:
Size is:16

You could argue that you already know the size of the entire array using sizeof - you've got it in your original malloc call - 100 * sizeof(int). Although the malloc machinery must know the amount of memory associated with the pointer internally (it needs it for a corresponding free call), and apparently some implementations provide functions to return this information, as far as I know there is not implementation-independent and portable way of doing this without handling it yourself.

Related

Why is it possible to add define elements in an array of length 0 in C++ [duplicate]

This question already has answers here:
Array with size 0 [duplicate]
(4 answers)
What is the purpose of allocating a specific amount of memory for arrays in C++?
(5 answers)
Closed 5 years ago.
Im reading up for a exam in C++ and just fideling around in order to get a better sense of the language. My understanding is that arrays in c++ are defined with a fixed length either before run time or dynamically. Knowing this I don't understand why C++ accepts this. I wouldn't think that it would be possible to add element to an array of length 0;
int * TestArray = new int[0];
TestArray[0]=10;
TestArray[1]=20;
TestArray[2]=30;
Writing to array elements outside of the valid size is Undefined Behaviour. It's a bug and your program is ill formed. But the compiler is not required to issue a diagnostic (although most will with the right warning options).
It's your responsibility to follow the rules.
You may not access any elements in a zero sized array. It results in undefined runtime behavior.
However, zero sized arrays are allowed for various reasons.
First, it allows you to make functions less complicated by skipping size checks:
void f(size_t n)
{
int * ptr = new int[n];
//...
delete[] ptr;
}
instead of:
void f(size_t n)
{
if (n>0)
{
int * ptr = new int[n];
//...
delete[] ptr;
}
}
Second, the intent was to make it easy for compiler writers to implement new using malloc, and this is the defined behavior for malloc.
The GCC c compiler docs give this reason:
"Zero-length arrays are allowed in GNU C. They are very useful as the last element of a structure that is really a header for a variable-length object: "
struct line {
int length;
char contents[0];
};
struct line *thisline = (struct line *)
malloc (sizeof (struct line) + this_length);
thisline->length = this_length;
[without it], you would have to give contents a length of 1, which means either you waste space or complicate the argument to malloc.
My professor told me that because c++ and c can access and write outside of array bounds,it is one of the main reasons they are used to create operating systems. For example you can even do something like
arr[-1]=5;
I believe it is worth mentioning.However this can lead to undefined behavior.

how can i know the number of elements in array [duplicate]

This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
Closed 8 years ago.
i run the following code but it kept printing "4"
why its printing "4" and not "12"? and can I use malloc and then sizeof?(if i can then how)
#include<stdio.h>
int main()
{
int arr1[3]={1,2,3};
int *arr2=arr1,i;
printf("%d",sizeof(arr2));
return 0;
}
Pointers are not arrays. arr2 is a pointer to int. sizeof(arr2) will return size of pointer. To print size of an array, the operand of sizeof must be of an array type:
printf("%u",sizeof(arr1));
can I use malloc and then sizeof?
No. There is no portable way to find out the size of a malloc'ed block. malloc returns pointer to the allocated memory. sizeof that pointer will return size of the pointer itself. But you should note that, there is no need to use sizeof when you allocate memory dynamically. In this case you already know the size of array. (In case of char array use strlen).
Further reading: c-faq: Why doesn't sizeof tell me the size of the block of memory pointed to by a pointer?
sizeof(arr2)
would print the size of pointer as it's a int*. However, if you try sizeof(arr1), it would print
sizeof(element_type) * array_size
i.e size of array. Remember that it's not taking into account how many elements are there in array. It would just consider how many elements can array store.
arr2 is a pointer and you are printing sizeof(pointer)
sizeof(arr1) will give you sizeof array which might give you 12.(Given your integer is 4 bytes)
It's printing 4 because arr2 is a pointer, and the size of a pointer is 4 bytes in 32bit architectures. You can't know the size of a dynamically allocated array ( array allocated with malloc ) given just a pointer to it.

What should I do to get the size of a 'dynamic' array? [duplicate]

This question already has answers here:
How do I find the length of an array?
(30 answers)
Closed 8 years ago.
I have this code.
int x[5];
printf("%d\n",sizeof(x) );
int *a;
a = new int[3];
printf("%d\n",sizeof(*a));
When I pass a 'static' array to sizeof(), it returns the dimension of the declared array multiplied by the number of bytes that the datatype uses in memory. However, a dynamic array seems to be different. My question is what should I do to get the size of an 'dynamic' array?
PD: Could it be related to the following?
int *a;
a=new int[3];
a[0]=3;
a[1]=4;
a[2]=5;
a[3]=6;
Why can I modify the third position if it's supposed I put a 'limit' in "a=new int[3]".
When I pass a 'static' array to sizeof(), it returns the dimension of the declared array multiplied by the number of bytes that the datatype uses in memory.
Correct, that is how the size of the entire array is computed.
However, a dynamic array seems to be different.
This is because you are not passing a dynamic array; you are passing a pointer. Pointer is a data type with the size independent of the size of the block of memory to which it may point, hence you always get a constant value. When you allocate memory for your dynamically sized memory block, you need to store the size of allocation for future reference:
size_t count = 123; // <<== You can compute this count dynamically
int *array = new int[count];
cout << "Array size: " << (sizeof(*array) * count) << endl;
C++14 will have variable-length arrays. These arrays will provide a proper size when you check sizeof.
Could it be related to the following? [...]
No, it is unrelated. Your code snippet shows undefined behavior (writing past the end of the allocated block of memory), meaning that your code is invalid. It could crash right away, lead to a crash later on, or exhibit other arbitrary behavior.
In C++ arrays do not have any intrinsic size at runtime.
At compile time one can use sizeof as you showed in order to obtain the size known to the compiler, but if the actual size is not known until runtime then it is the responsibility of the program to keep track of the length.
Two popular strategies are:
Keep a separate variable that contains the current length of the array.
Add an extra element to the end of the array that contains some sort of marker value that indicates that it's the last element. For example, if your array is known to be only of positive integers then you could use -1 as your marker.
If you do not keep track of the end of your array and you write beyond what you allocated then you risk overwriting other data stored adjacent to the array in memory, which could cause crashes or other undefined behavior.
Other languages tend to use the former strategy and provide a mechanism for obtaining the current record of the length. Some languages also allow the array to be dynamically resized after it's created, which usually involves creating a new array and copying over all of the data before destroying the original.
The vector type in the standard library provides an abstraction over arrays that can be more convenient when the size of the data is not known until runtime. It keeps track of the current array size, and allows the array to grow later. For example:
#include <vector>
int main() {
std::vector<int> a;
a.push_back(3);
a.push_back(4);
a.push_back(5);
a.push_back(6);
printf("%d\n", a.size());
return 0;
}
As a side-note, since a.size() (and sizeof(...)) returns a size_t, which isn't necessarily the same size as an int (though it happens to be on some platforms), using printf with %d is not portable. Instead, one can use iostream, which is also more idiomatic C++:
#include <iostream>
std::cout << a.size() << '\n';
You do not, at least not in standard C++. You have to keep track of it yourself, use an alternative to raw pointers such as std::vector that keeps track of the allocated size for you, or use a non-standard function such as _msize https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/msize?view=msvc-160 on Microsoft Windows or malloc_size https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/malloc_size.3.html on MacOS X.

sizeof works unusual at c++ after array creation [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to find the sizeof(a pointer pointing to an array)
I am creating an array by using following code
float *A;
A = (float *) malloc(100*sizeof(float));
float *B;
B = (float *) malloc(100*sizeof(float));
but after these when I type an print the size of the A and B by the following, I get 2 as a result as I expect to see 100.
sizeof(A)/sizeof(float)
Your expectation is wrong. A is a float*, so its size will be sizeof(float*), regardless of how you actually allocate it.
If you had a static array - i.e. float A[100], then this would work.
Since this is C++, use std::array or std::vector.
Worst case, use new[]. Definitely don't use malloc.
This works only for static arrays, defined in the current scope.
All you get in your example is the size of a pointer to float divided by the size of float.

length of dynamic array in c++ [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to find the sizeof(a pointer pointing to an array)
I declared a dynamic array like this:
int *arr = new int[n]; //n is entered by user
Then used this to find length of array:
int len = sizeof(arr)/sizeof(int);
It gives len as 1 instead of n . Why is it so?
Because sizeof does not work for dynamic arrays. It gives you the size of pointer, since int *arr is a pointer
You should store the size of allocated array or better use std::vector
Because arr is not an array, but a pointer, and you are running on an architecture where size of pointer is equal to the size of int.
Andrew is right.
You have to save n somewhere (depends on where do you use it). Or if you are using .NET you could use Array or List...