0

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 
1
  • "I'm trying to implement this code". No. You don't implement code. You implement an algorithm, an idea, anything, with code. If you have code, it's already implemented, even if it's not doing what you need. Commented May 27, 2015 at 9:55

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.