Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

2D Array Problem

Status
Not open for further replies.

Butterflies

Programmer
Mar 23, 2005
4
0
0
US
The previous post was a little messed up, sorry...here is the message again.

Note that we are just BEGINNER C programmers...and we need help! Any help is very much appreciated...thank you!

We were trying to figure out how to input variables into 2D arrays. For example if there are 2 variables named "hi" and "hello" and they represent the numbers "1" and "2" respectively, can we have something like "int array[hi][hello]" so that there are 1 row and 2 columns? We are really stuck on that part. Thanks!
 
not clear what the task is....

int hi = 1, hello = 2;
int arr[hi][hello];
 
Yeah that's what we're trying to do...is it even possible? Thanks for replying!
 
well,you can't do that.
"hi" and "hello" needs to be constants.
Therefore you should do:
#define hi 1
#define hello 2
....
...
int arr[hi][hello];
 
Here is an example:

#include<stdio.h>
#define hi 5
#define hello 2
void main()
{
int i, j, k;
int array[hi][hello] = {0};
k = 1;
/* input the array */
printf(&quot;Array input\n&quot;);
for( i = 0; i < hi; i++ )
{
for( j = 0; j < hello; j++ )
{
printf(&quot;value%d = &quot;, k );
scanf(&quot;%d&quot;,&array[j]);
k++;
}
}
/* output the array*/
printf(&quot;\nArray output\n&quot;);
for( i = 0; i < hi; i++ )
{
for( j = 0; j < hello; j++ )
{
printf(&quot;array[%d][%d] = %d\n&quot;, i, j, array[j]);
}
}
}
 
Ohh...I see now. Thanks so much!
But what if you don't know what &quot;hi&quot; and &quot;hello&quot; is beforehand, until a user inputs them?
 
Try this:

#include<stdio.h>
#include<stdlib.h>
#define _MAXSIZE_ 100
typedef int RowArray[_MAXSIZE_];
void main()
{
int hi, hello;
int i, j, k;
RowArray *array;
k = 1;
/* input the array */
printf(&quot;Array input\n&quot;);
printf(&quot;Enter the value of \&quot;hi\&quot;: &quot;);
scanf(&quot;%d&quot;,&hi);
printf(&quot;Enter the value of \&quot;hello\&quot;: &quot;);
scanf(&quot;%d&quot;,&hello);
array = ( RowArray * )malloc(hi * hello * sizeof(int));
for( i = 0; i < hi; i++ )
{
for( j = 0; j < hello; j++ )
{
printf(&quot;value%d = &quot;, k );
scanf(&quot;%d&quot;,&array[j]);
k++;
}
}
/* output the array*/
printf(&quot;\nArray output\n&quot;);
for( i = 0; i < hi; i++ )
{
for( j = 0; j < hello; j++ )
{
printf(&quot;array[%d][%d] = %d\n&quot;, i, j, array[j]);
}
}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top