Jump to content

C++ Array Problem

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
dksmarte

dksmarte

    Newbie

  • Members
  • Pip
  • 2 posts
I'm trying to create an array of varying length depending on the input of the user as demonstrated in the following code:

#include <iostream.h>


int main(void)

{

	int size;

	cout << "Enter array size: ";

	cin >> size;

	

	int data [size];

	

	return 0;

}

When I compile, I get the following error:

Quote

Error E2313 test.cpp 9: Constant expression required in function main()

Can anyone enlighten me on how to circumvent this error?

#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
Your problem is just what the error says: you are not allowed to dynamically determine the size of an array that way. You will either have to use the new[] operator and a pointer, or use a container class from the STL.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
bobwrit

bobwrit

    Newbie

  • Members
  • PipPip
  • 28 posts
I've tried this a few times and it hasn't worked for me so in my opinion you cant declare a array of variable size.

#4
Deathcry

Deathcry

    Learning Programmer

  • Members
  • PipPipPip
  • 68 posts

dksmarte said:

I'm trying to create an array of varying length depending on the input of the user as demonstrated in the following code:

#include <iostream.h>


int main(void)

{

	int size;

	cout << "Enter array size: ";

	cin >> size;

	

	int data [size];

	

	return 0;

}

When I compile, I get the following error:



Can anyone enlighten me on how to circumvent this error?

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
int size;
cout << "Enter array size: ";
cin >> size;

int data [size];

return 0;
}

ur main is all messed up. try that...
the code is with you

#5
v0id

v0id

    Retired

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,936 posts
I would create the array dynamically, using the new-operator.
#include <iostream>

int main()
{
	int *arr;
	int  arr_Size;
	
	std::cout << "Array size: ";
	std::cin  >> arr_Size;
	
	arr = new int[arr_Size];
	
	// Use the array in different ways
	
	delete [] arr;
	return 0;
}