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.
Related
This question already has answers here:
How do you 'realloc' in C++?
(4 answers)
Closed 2 years ago.
I have made a code in which i am creating array of objects using new.I am extending the array by another new keyword and last index of previous array like following.Its working fine(The constructor is printing "a" number of times the net index). But i dont know is it safe or not? My main motive is to make a dynamic array but i cant use malloc because it dows not call constructors.So i am using new. But idont know how to reallocate memory after using new. If i use realloc then the program is not giving any error but realloc is not calling the constructor.
Summary:->Just want to call constructor while reallocating memory.
I have given the image of my code
class xy
{
unsigned x[10],y[10],counter;
public:
xy()
{counter=0;}
void setxy(unsigned a,unsigned b)
{x[counter]=a;y[counter]=b;counter++;}
void printxy()
{for(unsigned i=0;i<counter;i++)cout<<"="<<x[i]<<"^3+"<<y[i]<<"^3";}
};
class unitcell
{
unsigned long long value_cube,hasharr_len;
xy* hasharr;
unsigned long long* r_numberindexes;
unsigned rarraylen;
public:
unitcell()
{cout<<"a";}
unsigned long long gethasharraylen()
{return hasharr_len;}
};
int main()
{
unitcell *a=new unitcell[3];
unitcell *b=a+3;
b=new unitcell[3];
}
No.
First you're initializing b to the value of a+3 and then you're assigning the result of new to it, which will be a completely different value. You have no control over where your allocated memory will end up. You should assume each new invocation gives you a completely random address, whose value you cannot predict.
If you want to "extend" your array you have to allocate a bigger one, copy all the elements you already had and then delete the old one
unitcell *b = new unitcell[6];
std::copy(a, a+3, b);
delete a;
a = b;
STL class std::vector works in this way internally.
This question already has answers here:
Flexible Array Member (Zero Length Array) [duplicate]
(2 answers)
How to include a dynamic array INSIDE a struct in C?
(8 answers)
Closed 8 years ago.
I have seen the usage of this statement in driver programs at the end of the structure.
Can anyone explain me what is the use of this statement? and how does it works internally?
I mean will compiler considers it as array or a variable?
In C, it's a trick to allow you to put a variable-sized array at the end of a structure, by allocating enough memory for both the fixed-sized fields and whatever you want in the array. For example:
struct array {
size_t size;
int a[]; // strictly, it should be incomplete rather than zero sized
};
struct array * make_array(size_t size) {
struct array * array = malloc(sizeof (struct array) + size * sizeof (int));
array->size = size;
return array;
}
struct array * array = make_array(2);
array->a[1] = 42; // No problem: there's enough memory for two array elements
In C++, it's not valid. Use std::vector instead.
While arrays of size 0 are not supported by either standard, many compilers allow them as an extension. The standardised C way (C99+) instead leaves out the size altogether.
Thiis is used to describe a data-structure consisting of the starting fields and a variable number of array elements, as well as for comfortable access to them.
This question already has answers here:
May I treat a 2D array as a contiguous 1D array?
(6 answers)
Closed 8 years ago.
Related thread here: Does C99 guarantee that arrays are contiguous?
Apparently answer() isn't valid below, but could be re-written to use char * or cast to int[nElements] (possibly). I'll admit I don't understand the standard references and why a contiguous block of int couldn't be accessed via int* if properly aligned.
First is the following code block valid on most C++ platforms?
void answer(int *pData, size_t nElements)
{
for( size_t i=0; i<nElements; ++i )
pData[i] = 42;
}
void random_code()
{
int arr1[1][2][3][4]; // local allocation
answer(arr1, sizeof(arr1) / sizeof(int));
int arr2[20][15];
answer(arr2, sizeof(arr2) / sizeof(int));
}
Second does answer() remain valid for all allocation types (global, local, heap(hopefully correct!))?
int g_arr[20][15]; // global
void foo() {
int (*pData)[10] = new int[50][10]; // heap allocation, at least partially
answer(&pData[0][0], 50*10);
// not even sure if delete[] will free pData correctly, but...
}
Yes, most platforms will indeed pack the elements of an N-dimensional array in such a way that linear addressing on a pointer to the first element will find all of the elements.
It is actually hard (as in, I cannot figure it out) to come up with a standards compliant implementation that does not do this, as an array of arrays must pack said arrays, and the size of the array of arrays is the size of each sub array times the number of arrays of arrays. There does not seem to be room for it not to work. Even the ordering of each element seems to be well defined.
Despite this, no clause in the standard I am aware of lets you actually reinterpret the pointer to the first element of a multi dimensional array as a pointer to an array of the product. Many clauses talk about how you can only access the elements of the array, or one-past-the-end.
The code in answer() is fine. The code in random_code() is misusing answer() (or not calling the overload of answer() shown in the question). It should be:
void random_code()
{
int arr1[1][2][3][4];
answer(&arr1[0][0][0][0], sizeof(arr1) / sizeof(int));
int arr2[20][15];
answer(&arr2[0][0], sizeof(arr2) / sizeof(int));
}
The code in answer() expects an int *; you were passing an int (*)[2][3][4] and an int (*)[15], neither of which looks like int *.
This remains valid for other allocation mechanisms that allocate a single contiguous block of data, such as the ones shown.
As the previous person said, there's a type error in your code. You're trying to use an int ()[X] type actual argument for an int formal argument. So to make your code work, you should use type casting.
C++/C uses the same memory layout for data types not depending on what section of memory is used for allocating an object so that the same code can be used for values where they are. So the answer to your second question, is if your code is working on stack-allocated values, it is going to work with a heap-allocated value too.
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.
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...