|
-
May 19th, 2011, 11:27 AM
#5
Re: fstream with dynamically allocated arrays
 Originally Posted by ejohns85
Ok thanks, I understand that now. However, I'm now confused why my attempt with the static array worked. If I used "float x[3]" instead of "float* x = new float[3]", with "out.write((char*)x, sizeof(x))", then why does "sizeof(x)" make sense? I thought that if you declare a static array x, then x actually represents a pointer to the start of the array,
Arrays are not pointers, and pointers are not arrays. An array is a type, a pointer is a type, they are not the same thing.
Code:
int x[3]; // this is of type array of 3 ints
int *px; // this is of type pointer to int.
Secondly, sizeof() is a compile-time value. It cannot be used to determine run-time sizes.
Code:
cout << "Input the number of value: ";
int n;
cin >> n;
float* x = new float[n];
So how is sizeof() going to know what "n" is?
I thought that if you declare a static array x, then x actually represents a pointer to the start of the array,
No, x is an array if you declare an array. See above.
What you are confused about is that an array, if you pass it to a function, decays to a pointer. That is a totally different situation than if you declare an array, declare a pointer, and believe they are the same thing (when they are not).
Regards,
Paul McKenzie
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|