Reputation: 5
I was learning arrays for like 3 to 4 days , and I get stuck on this task. What actually i need to do is replacing the values from first to second array but the column needs to be one half and that half to replace in rows. For example: We insert for n = 3; then the first array column is n*2 Like this
1,2,3,4,5,6
7,8,9,10,11,12
13,14,15,16,17,18
And the exit need to be
1,2,3
7,8,9
13,14,15
4,5,6
10,11,12
16,17,18
And the code that i write
#include <stdio.h>
int main ()
{
int n,m;
scanf("%d",&n);
int a=n*2,b=n;
m=n*2;
int firstarray[n][m],secondarray[a][b];
int i,j,k,l;
for(i=0;i<n;i++)
for(j=0;j<m;j++)
scanf("%d",&firstarray[n][m]);
for(i=0;i<n;i++)
for(j=0;j<m/2;j++)
secondarray[i][j]=firstarray[i][j];
for(i=0;i<n;i++){
for(j=m/2;j<m;j++)
{
for(k=n;k<a;k++)
for(l=0;l<b;l++)
secondarray[k][l]=firstarray[i][j];
}
}
for(i=0;i<a;i++)
{
for(j=0;j<b;j++){
printf("%d",secondarray[i][j]);
}
printf("\n");
}
}
Upvotes: 0
Views: 59
Reputation: 23218
In this section, the scanf statement is attempting to access an array element that is out of bounds :
for(i=0;i<n;i++)
for(j=0;j<m;j++)
scanf("%d",&firstarray[n][m]);//use i,j indexes, not n,m initializers
I think this is probably just a typo, but using n
& m
this way exceeds the bounds of the array by 1 in each dimension.
Change to:
for(i=0;i<n;i++)
for(j=0;j<m;j++)
scanf("%d",&firstarray[i][j]);
^ ^
Note that there are other problems downstream in your logic to do what you are showing. It is not a simple transpose where given your example input, the result would be:
1, 7, 13
2, 8, 14
3, 9, 15
4, 10, 16
5, 11, 17
6, 12, 18
Keeping in mind the shape of your original array is stored in memory as a contiguous series of int
locations:
|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|
So to do what you show the first loop series will need to assign values to the [6][3]
array by a combination of picking the 1st three in memory, skip the next 3, and so on:
|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|
^ ^ ^ ^ ^ ^ ^ ^ ^
Then to pick up the rest, start by skipping 3, assigning 3, skipping..., and so on.
|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|
^ ^ ^ ^ ^ ^ ^ ^ ^
This then requires playing with the indexing to get this transformation, so given your arrays are created as:
m=n*2;
int firstarray[n][m],secondarray[m][n];
And the inputs are given as shown in your post, populating secondarray
is done in 2-stages:
//get first 3 of 6 columns
for(i=0;i<n;i++)
{
for(j=0;j<m/2;j++)
{
secondarray[i][j]=firstarray[i][j];
}
}
//get second 3 of 6 columns
for(i=0;i<n;i++)
{
for(j=3;j<m;j++)
{
secondarray[i+3][j-3]=firstarray[i][j];
}
}
Upvotes: 1