Variable for Array Size??

Is it not kosher to declare an array the size of a variable?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//bubble sort

#include<iostream>
using namespace std;

int main()
{
	int size, x;
	cout << "Enter how many numbers you would like to sort: ";
	cin >>  size;
	float data[size];	 //  ***error C2057: expected constant expression***
                         // if I use a constant instead of the variable [size] the code compiles   

	for (int b=0; b<size; b++)	{		//data entry
		cout << "\nEnter data point " << b+1 << ": ";
		cin >> data[b];
	}
	for (int b=0; b<size; b++)	{	//data output not sorted
		cout << data[b] << "\n";		
	}
	cin >> x;
	return 0;
}
Last edited on
Kosher?
http://en.wikipedia.org/wiki/Kosher_foods

Kosher foods are those that conform to the rules of Jewish religion.
These rules form the main aspect of kashrut, Jewish dietary laws.
Last edited on
Kosher can also mean good, in a sense. I've heard it used like that a few times.

When an array is declared using type array[size];, the compiler goes through and sets the commands to create all of the arrays before-hand, and if a variable isn't constant, then the compiler won't be able to set up the memory allocation for the array (since the variable might not have been set, and the compiler can't predict how the program will flow when executed). However, you can always do this:

float* data = new float[size];

But then you have to delete your array before the program ends.
Last edited on
Thanks.
I understand why the compiler doesn't like it.
I am just learning, the program itself is not important.
And I just started learning pointers.

Could you please elaborate a bit on the line of code?
Is it a pointer of some sort?
I haven't seen the * symbol at the end of a type.
Thanks!
Yes it is a pointer.

float *data = new float[size];

First you're declaring a pointer to a float. After the assignment is the word new float[size]. new returns a pointer to memory that is allocated at runtime. You're basically saying you want to allocate enough space to store 20 floats. You can then index the pointer just like data[0] and that will return the first value as it would normally.

Before the program ends you need to write this:
delete[] data;

That frees the memory that has been allocated using new. If you don't do that, the memory won't be freed.

The pointer data will still exist and it will still point to the area in memory where the array was, but the array has been deallocated and may be overwritten.
Last edited on
Thanks!!

I tried using a pointer before posting, but not in the correct manner, and have not encountered new yet.

Last edited on
Topic archived. No new replies allowed.