Noober
Noober

Reputation: 1626

Error in C code while using 2d array

I am trying to implement this simple code(no algo as such).

#include<stdio.h>
#include<stdlib.h>

int main()
{
    int l,h1,h2,h3,i,j,t,m,n;
   scanf("%d %d",&m,&n);

    int A[m][n];
    for(i=1;i<=m;i++)
       {
            for(j=1;j<=n;j++)
             scanf("%d",&A[i][j]);
       }

    int n1=m*n;
    int adj[n1][n1];
    printf("Before initialization array A =\n");
    for(i=1;i<=m;i++)
        {
            for(j=1;j<=n;j++)
                printf("%d ",A[i][j]);
            printf("\n");

        }
    for(i=1;i<=n1;i++)
        {
          for(j=1;j<=n1;j++)
             adj[i][j]=-1;
        }
    printf("After initialization array A =\n");
    for(i=1;i<=m;i++)
        {
          for(j=1;j<=n;j++)
            printf("%d ",A[i][j]);
            printf("\n");

       }
    return 0;
}

This is my input file -

4 3 
2 3 2
2 5 1
5 3 1
3 1 1

So here 1st 2 elements are m,n i.e. no of rows and columns.Then for m rows there are n elements.I store these elements in a 2d array A. I then print this array.It gives the correct answer.Then I am making new arrary adj[m*n][m*n].I initialize this array to -1.After that when I print my A array back first five element of A also becomes -1.I am not changing value of A.So why is this happening.This is the output I get-

Before initialization array A =
2 3 2 
2 5 1 
5 3 1 
3 1 1 
After initialization array A =
-1 -1 -1 
-1 -1 1 
5 3 1 
3 1 1 

Upvotes: 0

Views: 62

Answers (2)

Spikatrix
Spikatrix

Reputation: 20244

C uses 0 based indexing. So, the valid indices of an array start from 0 and end at length-1.

This means that you'll have to modify your loops. This:

for(i=1;i<=m;i++)

and needs to be

for(i=0;i<m;i++)

You'll need to do the same for the all the other loops. Otherwise, you access an invalid array index and this leads to Undefined Behavior.

Upvotes: 2

Aqeel Abbas
Aqeel Abbas

Reputation: 169

What you need to know is that in C/C++ array starts from 0 to array length -1. Change this in for loops and see what happens

Upvotes: 1

Related Questions