0

Here is some sample jave code. Is this possible in C++ too?

public class Example {
    public static void main(String args[]){
        int[][] a = new int[3][];
        a[0] = new int[]{1};
        a[1] = new int[]{1,2};
        a[2] = new int[]{1,2,3};
        display(a);
  }
}
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
xaero
  • 99
  • 1
  • 1
  • 10

3 Answers3

7

If the question is: "Is it possible to do X in Turing Complete Language Y when it can be done in Turing Complete Language Z?" Then answer is yes. It's always yes.

OmnipotentEntity
  • 16,531
  • 6
  • 62
  • 96
3

You should use a pointer to pointers, alike argv that you receive from main(char **argv, ... argc)

a string is a array of chars, and argv is an pointer for that scructure.

You should use int **a, then create line by line in memory,

a should point:

a[0] => unnamed pointer => 0, 0, 0
a[1] => unnamed pointer => 0, 0

like when you do

argv[0] = "my program's name"
argv[1] = "my first param"

when whe use char strings there's an '\0' char at the end, so it's possible to know when it finishes, in that case must have some king of control, unlike Java in C you can overflow.

Rodrigo Gurgel
  • 1,696
  • 2
  • 15
  • 32
  • I think I can do this, sounds a bit tricky as I am a Java programmer, but I think I can manage it.. thanks:) – xaero Jul 20 '12 at 19:44
  • That will work, sure, but it's needlessly complicated. Don't use C++ to program in C. :( – OmnipotentEntity Jul 20 '12 at 19:48
  • Read about malloc, if you're in C++ use new witch is more simple and can handle constructors, so something like: int *pointer_to_line = new int[ 10 ] // for ten cols, then make int **a points to pointer_to_line ( a[0] = pointer_to_line ), ok you've done with this line, next line the same thing. for a[1], etc. – Rodrigo Gurgel Jul 20 '12 at 19:51
  • 1
    They are coming from Java and even if they weren't I'd still recommend the object oriented solution of `std::vector>` first for C++ – AJG85 Jul 20 '12 at 19:54
1

Yes.

It is possible. You can do everything in C++.

DanDan
  • 10,462
  • 8
  • 53
  • 69