/* Some simple examples of arrays and 2d arrays of vectors. Laura Toma, February 2018 */ #include #include #include #include using namespace std; //a structure for a point in 2D typedef struct _point2d { double x, y; } point2d; int main(int argc, char** argv) { //get the arguments right if (argc !=2 ) { printf("Usage: %s n\n", argv[0]); exit(1); } int n = atoi(argv[1]); printf("you entered n=%d\n", n); int i, j; double sum; /***************test1 *********************/ //an array of n ints, C style int *a; /* DON'T DO THIS: int a[n]; It's wrong and you're sure to get segfaults for larger values of n. YOU NEED TO ALLOCATE dynamically using malloc() because you don't know n at compile time. */ //allocate the space dynamically a =(int*)malloc(n * sizeof(int)); //put some data in it for (i=0; i c; //put some data in it for (i=0; i *d; /* DON'T DO THIS: vector d[n]; It's wrong and you're sure to get segfaults for larger values of n. YOU NEED TO ALLOCATE dynamically using new because you don't know n at compile time. */ //allocate the space dynamically d = new vector [n]; //NOTE: we assume that c++ calls the constructor to create a new Vector at each d[i] //put some data in it for (i=0; i *e; /* DON'T DO THIS: vector e[n]; It's wrong and you're sure to get segfaults for larger values of n. YOU NEED TO ALLOCATE dynamically using new because you don't know n at compile time. */ //allocate the space dynamically e = new vector [n]; //NOTE: we assume that c++ calls the constructor to create a new Vector at each e[i] //put some data in it for (i=0; i **grid; /* DON'T DO THIS: vector grid [n][n] It's wrong and you're sure to get segfaults for larger values of n. YOU NEED TO ALLOCATE dynamically using new because you don't know n at compile time. */ //allocate first an array of vector* grid = new vector* [n]; for (i=0; i [n]; } //put some data in it for (i=0; i