Writing an Array

Posted 27 October 2006 - 02:52 PM

i need to write a program that sets up a table displaying values of n, sqrt n and ln n from n = 0 - nmax. Ive prompted the user to enter a value for integer nmax. but then ive no idea how to make this apply for the value for nmax for my table.

Re: Writing an Array

Posted 27 October 2006 - 11:59 PM

in c++, arrays exist on the stack. and the program must tell the kernel ahead of time how much memory to allocate on the stack. in this case, you do not know how much memory you will need ahead of time, instead you will only know at run time. in this case you need to use dynamic memory allocated which can be easily accomplished by use of pointers.

for instance, take your same code, and implement pointers in place of the static array. it would look like so

i am assuming that you are trying to get numRows to change with n. However, this will only assign n as the value of numRows at that very moment. if n changes later, numRows will not. I simply removed the variable.

next, input was requested from the user and that value was assigned to n. then dynamic memory allocated happens by use of the new keyword.

double *table[numColumns] makes an array of integer pointers, 'numColumns' long, this sets up the first dimension of the table. then, by use of a for loop, 'n' integers are allocated and tied to each pointer in the list.

for (int y = 0;y < numColumns;++y)
{
table[y] = new int[n];
}

we then display this table by use of a double for-loop. the outer for loop traverses the rows of the table, and the inner for loop traverses the columns of the table. for each row of the table, 'n' columns will be displayed, and then the loop will move to the next row until no more rows are left to be displayed.