-7

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)
3
  • 7
    use std::vector Commented Jan 27, 2013 at 0:30
  • Your expectation, that the size of a pointer should change if you change what it's pointing to, is unreasonable. (Now, if this was an array passed to a function, you'd have a point.) Commented Jan 27, 2013 at 0:40
  • 1
    -1 solely for being moronic to helpful experts in comments Commented Jan 27, 2013 at 3:12

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

12 Comments

@Erogol there would be if you took good advice and stop writing C code and labeling it C++. Use vector or array.
@Erogol so, wait, do you want to learn C or C++? You do know they're different, right?
@Erogol If you tag your question C++, expect C++ answers.
@Erogol Sorry, you can't have an account here if you're under 13.
@Erogol Stop throwing tantrums like a spoiled stubborn child. You got your answer already. Annoy and insult more people who try to help you even though they don't have to, see how well that goes~
|
4

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.