2

In my program I want to pass a pre initialized 2D array through a function. I am getting the 1st element correctly but rest of them are initialized to 0 while passing. I am not getting why this problem is arising. I don't want to use pointers to pass array. Please tell if I can pass my 2D array without using pointers . Here is the code -

#include<stdio.h>
#define MAX(a,b) (a>b)?a:b

int kat(int S,int A[][S])
{
  int i,j,r[S];
  r[0] = A[0][0];
  j = 0;
  for(i=1;i<S;i++)
  {
     r[i] = MAX(r[i-1] + A[i][j],r[i-1] + A[i][j+1]);
     if (r[i-1] + A[i][j] < r[i-1] + A[i][j+1])
     j = j+1;
  }
  return r[S-1];
}

int main()
{
  int A[100][100],T,S,i,j,k,ans;
  scanf("%d",&T);
  while(T--)
  {
     i=0;
     scanf("%d",&S);
     for(k=1;k<=S;k++)
     {
       for(i;i<k;i++)
       {
         for(j=0;j<=i;j++)
         {
           scanf("%d",&A[i][j]);
         }
       }
     }
     ans = kat(S,A);
     printf("%d\n",ans);
  }
}

1 Answer 1

2

The problem is that you are lying to the compiler: you tell it that the array that you are going to pass to kat is int[][S], where S is a variable, but in realty you are passing it an array int[][100], where 100 is a constant.

You can fix this by declaring the array after reading S in the main, like this:

scanf("%d",&S);
int A[S][S];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.