Re: Is Linux Unix?
- To: debian-user@lists.debian.org
- Subject: Re: Is Linux Unix?
- From: Jeronimo Pellegrini <pellegrini@mpcnet.com.br>
- Date: Sun, 1 Aug 2004 11:40:39 -0300
- Message-id: <[🔎] 20040801144039.GB27104@randomnode.info>
- In-reply-to: <e10cccdf.0407262032.68586f60@posting.google.com>
- References: <06E2E60FB9C6EF409EFE472A8F4A82EBCDE6FC@coso.staff.vuw.ac.nz> <e10cccdf.0407222359.64ad3060@posting.google.com> <20040723223237.GB2030@mesanetworks.net> <e10cccdf.0407231854.14f692a0@posting.google.com> <4101F020.6090001@bigfoot.com> <e10cccdf.0407262032.68586f60@posting.google.com>
> There's another problem with the above C++ code: If ny and nz
> aren't constant, you can't write
>
> double s[ny][nz];
>
> Instead, either you allocate the array in two stages:
>
> double** s = new (double*)[ny];
> for (j=0; j < ny; ++j) s[j] = new double[nz];
Actually, the first version works -- and both C and C++ (tested here with
gcc -- not sure it it became a standard or not)) will dynamically allocate
memory for you. Try this:
#include <iostream>
using namespace std;
int main() {
int size1, size2, i, j;
cin >> size1;
cin >> size2;
double vec[size1][size2];
for (i=0; i<size1; i++)
for (j=0; j<size2; j++)
vec[i][j] = i+j;
cout << endl;
for (i=0; i<size1; i++) {
for (j=0; j<size2; j++)
cout << vec[i][j] << " ";
cout << endl;
}
}
And enter something like "1000" and "1000" when asked for the array dimensions.
It compiles, runs, and does not segfault! :-)
The C version:
#include<stdio.h>
int main() {
int size1, size2, i, j;
scanf("%d", &size1);
scanf("%d", &size2);
double vec[size1][size2];
for (i=0; i<size1; i++)
for (j=0; j<size2; j++)
vec[i][j] = i+j;
puts("");
for (i=0; i<size1; i++) {
for (j=0; j<size2; j++)
printf("%f ",vec[i][j]);
puts("");
}
}
J.
Reply to: