variale array lenght help

hello, i want to ask for a number as an input during runtime and then create an 2-dimensional array of size as specified by user. i.e. if the user inputs 3, the array should be of size 3X3, and likewise...

could any one please help ???
You can do this in C (more specifically C99, the C language standard of 1999).

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stddef.h>
#include <stdio.h>

// ...

size_t sz;

printf("Input size: ");
scanf("%zu", &sz);

int matrix[sz][sz];

// now we can use matrix[x][y] 


In C++, you cannot legally do the above, although certain compilers allow it (such as GCC).
The C++ way to do this is to use a vector of vectors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <cstddef>
#include <iostream>
#include <vector>

// ...

std::size_t sz;

std::cout << "Input size: ";
std::cin >> sz;

std::vector<std::vector<int> > matrix(sz, std::vector<int>(sz));

// now we can use matrix[x][y] 


Edit: C example mistakes.
Last edited on
Btw, i use c++, standard one(the one with the blue editing screen).

And i dont have a vector header file. . .
Neither cstdef. . .
Last edited on
<vector> and <cstddef> are parts of the standard library, which means they are part of C++.

If you don't have them, then you don't have a proper C++ implementation.

I have no idea what you mean by "c++, standard one(the one with the blue editing screen)". C++ is a language, not a IDE or an editing tool.
@ dncp4312: what tools do you use?

If you use Pelles C IDE, be advised that it is for C only (C99 and C11) and does not support C++.
@catfish
I knw its compiler. . .
By editing screen, i meant the screen where you type the codes.
Here's what my compiler's about section displyays :
Turbo C++
Version 3.0
Copyright (c) 1990, 1992 by
Borland International, Inc.

I have version 4.5 too, but dont use it though. . .

One more thing, cud you please provide me with the download link of compiler you use. . .
Perhaps it is best that you upgrade to Visual Studio Express 2013 IDE:
http://www.visualstudio.com/en-us/downloads/download-visual-studio-vs#DownloadFamilies_2

If VS 2013 is too big and doesn't run well on your computer, try Orwell Dev-C++ IDE:
http://sourceforge.net/projects/orwelldevcpp/

Personally, I prefer using command line GCC and separate editor, instead of an IDE.
However if you're a beginner, this may be unpleasant, so you should use one of the above.
http://nuwen.net/mingw.html
http://www.sublimetext.com/
Thnx for help. . .
Nd i would like to knw, if you were able to recognize the compile i use. . .
Nd, yeah i am a beginner, currntly learning 2D arrays. . .
Last edited on
Thnx for help. . .
Nd i would like to knw, if you were able to recognize the compile i use. . .
Nd, yeah i am a beginner, currntly learning 2D arrays. . .

Friendly advice: write full words. Incomplete words may cause people to dislike you.
Okay, sorry, i am just habituated. . .
Thanks Anyways. . .
Topic archived. No new replies allowed.