how can i know the number of elements in array [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 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.

Related

Why dynamically allocated memory return different size that i actually tried to allocate? [duplicate]

This question already has answers here:
What is the size of a pointer? [duplicate]
(8 answers)
Closed 6 months ago.
I want to add a string after the struct in memory.
How to check that i dynamically allocated right amount of bytes?
Example:
const wchar_t* add_str = L"test string";
struct test_{
wchar_t* name;
size_t namelen;
} test;
void* ptest_void = malloc(sizeof(test) + wcslen(add_str)*sizeof(wchar_t));
// i cant dereference void*, hence, cant check sizeof(*ptest_void)
// then i try to get sizeof of a ptr which was cast to (test_*):
test_* ptest = (test_*)ptest_void;
size_t ptest_sz = sizeof(*ptest);
// ptest_sz has the size of _test struct, but without size of add_str...
free(ptest_void);
sizeof(ptest) doesn't tell you how much allocated memory ptest points to. It tells you the size in bytes of the variable ptest, most likely either 4 or 8 depending on your system.
There's also no standard way to check "how big" an allocated block of memory it. You're expected to keep track of that yourself.
If a call to malloc does not return NULL, that means the call was successful, and you can access as many bytes as you told it to allocate.

typecasting int [n][m] to int ** gives segmentation fault [duplicate]

This question already has answers here:
Why can't we use double pointer to represent two dimensional arrays?
(6 answers)
Closed 6 years ago.
int main()
{
matrix[2][4] = {{11,22,33,99},{44,55,66,110}};
int **ptr = (int**)matrix;
printf("%d%d",**matrix,*ptr);
}
But when a 2-d array is passed as a parameter it is typecasted into (*matrix)[2] ..
what type does the compiler store this array as... is it storing as a 2-d array or a double pointer or an pointer to an array .. If it is storing as an array how does it interprets differently at different situations like above. Please help me understand.
Is 2d array a double pointer?
No. This line of your program is incorrect:
int **ptr = (int**)matrix;
This answer deals with the same topic
If you want concrete image how multidimensional arrays are implemented:
The rules for multidimensional arrays are not different from those for ordinary arrays, just substitute the "inner" array type as element type. The array items are stored in memory directly after each other:
matrix: 11 22 33 99 44 55 66 110
----------- the first element of matrix
------------ the second element of matrix
Therefore, to address element matrix[x][y], you take the base address of matrix + x*4 + y (4 is the inner array size).
When arrays are passed to functions, they decay to pointers to their first element. As you noticed, this would be int (*)[4]. The 4 in the type would then tell the compiler the size of the inner type, which is why it works. When doing pointer arithmetic on a similar pointer, the compiler adds multiples of the element size, so for matrix_ptr[x][y], you get matrix_ptr + x*4 + y, which is exactly the same as above.
The cast ptr=(int**)matrix is therefore incorrect. For once, *ptr would mean a pointer value stored at address of matrix, but there isn't any. Secondly, There isn't a pointer to matrix[1] anywhere in the memory of the program.
Note: the calculations in this post assume sizeof(int)==1, to avoid unnecessary complexity.
No. A multidimensional array is a single block of memory. The size of the block is the product of the dimensions multiplied by the size of the type of the elements, and indexing in each pair of brackets offsets into the array by the product of the dimensions for the remaining dimensions. So..
int arr[5][3][2];
is an array that holds 30 ints. arr[0][0][0] gives the first, arr[1][0][0] gives the seventh (offsets by 3 * 2). arr[0][1][0] gives the third (offsets by 2).
The pointers the array decays to will depend on the level; arr decays to a pointer to a 3x2 int array, arr[0] decays to a pointer to a 2 element int array, and arr[0][0] decays to a pointer to int.
However, you can also have an array of pointers, and treat it as a multidimensional array -- but it requires some extra setup, because you have to set each pointer to its array. Additionally, you lose the information about the sizes of the arrays within the array (sizeof would give the size of the pointer). On the other hand, you gain the ability to have differently sized sub-arrays and to change where the pointers point, which is useful if they need to be resized or rearranged. An array of pointers like this can be indexed like a multidimensional array, even though it's allocated and arranged differently and sizeof won't always behave the same way with it. A statically allocated example of this setup would be:
int *arr[3];
int aa[2] = { 10, 11 },
ab[2] = { 12, 13 },
ac[2] = { 14, 15 };
arr[0] = aa;
arr[1] = ab;
arr[2] = ac;
After the above, arr[1][0] is 12. But instead of giving the int found at 1 * 2 * sizeof(int) bytes past the start address of the array arr, it gives the int found at 0 * sizeof(int) bytes past the address pointed to by arr[1]. Also, sizeof(arr[0]) is equivalent to sizeof(int *) instead of sizeof(int) * 2.
In C, there's nothing special you need to know to understand multi-dimensional arrays. They work exactly the same way as if they were never specifically mentioned. All you need to know is that you can create an array of any type, including an array.
So when you see:
int matrix[2][4];
Just think, "matrix is an array of 2 things -- those things are arrays of 4 integers". All the normal rules for arrays apply. For example, matrix can easily decay into a pointer to its first member, just like any other array, which in this case is an array of four integers. (Which can, of course, itself decay.)
If you can use the stack for that data (small volume) then you usually define the matrix:
int matrix[X][Y]
When you want to allocate it in the heap (large volume), the you usually define a:
int** matrix = NULL;
and then allocate the two dimensions with malloc/calloc.
You can treat the 2d array as int** but that is not a good practice since it makes the code less readable. Other then that
**matrix == matrix[0][0] is true

C++ - Arrays of the integer type [duplicate]

This question already has answers here:
How do I use arrays in C++?
(5 answers)
Closed 8 years ago.
I was just curious to know how to find the number of elements of an array of integers.
For character arrays we can loop thorough the array till we reach the null character,but how can I do it for integer array?
#include <iostream.h>
void main()
{
int a[] = {1,2,3,4};
for ( k = 0 ; a[k] ; k++)
cout<<k<<endl;
}
The above code counts from 0 to 8.
-A C++ noob with an open mind
A char array is terminated by 0 by convention. Such an array is called a C-style string, because it's used as a string of characters.
For integers, there is no termination value by convention, and you need to know the length by some other means. If it's your own array, store the length in a variable. If you receive the array from an API, there will be typically be a parameter receiving the length of the array, that you can use.
If the array is a global, static, or automatic variable (int array[10];), then sizeof(array)/sizeof(array[0]) works.
If it is a dynamically allocated array (int* array = malloc(sizeof(int)*10);) or passed as a function argument (void f(int array[])), then you cannot find its size at run-time. You will have to store the size somewhere.
Note that sizeof(array)/sizeof(array[0]) compiles just fine even for the second case, but it will silently produce the wrong result.

Find size of array pointed to by pointer [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 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.

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...