0

I have the code below.The problem is that I am taking a two dimensional array with a rows and 2 col.The 1st col is for storing values and 2nd as a flag.The problem arises when I initialize my flag the values are also getting affected.

#include<stdio.h>
    int main()
    {
        int a,b;
        scanf("%d%d",&a,&b);
        int arr[a][1];
        int i,j,k,sum=0;

        for(i=0;i<a;i++)
        {

            scanf("%d",&arr[i][0]);
        }
        for(i=0;i<a;i++)
        {

            printf("%d\n",arr[i][0]);
        }

        for(j=0;j<a;j++)
        {

           arr[j][1]=0;
        }
     for(i=0;i<a;i++)
        {

            printf("%d\n",arr[i][0]);//Different Values
        }
    }
1
  • have you tried step by step debbugig? Commented Jun 30, 2015 at 17:36

3 Answers 3

3

int arr[a][1]; There is only one column and not two.You should use

  int arr[a][2];
Sign up to request clarification or add additional context in comments.

Comments

2

Here you write out of bounds

arr[j][1]=0;

This is because you write to the second element of an array with only one element.

The size of arr[x] (for any valid x) is just one.

Writing out of bounds leads to undefined behavior.

2 Comments

How do u suggest I initialize my flag variable to zero then..Or should I go for 1D instead.
@reaper1 If you want two "colums" then declare it with two columns. Remember that the size you provide when declaring an array is the number of elements the array can hold, not the top index. So e.g. int arr[a][2] for an array that you can index as arr[x][0] and arr[x][1].
2

Your arrays should be something like this :

arr[row][col] where row denotes the number of rows and col the no of coloumns.

Therefore arr[a][1] is a array of a rows and 1 coloumn and therefore your code works wrong.

Your array should be a[a][2]. It means arr is a array with a rows and 2 coloumn.Similarly you have to change the other arr[][] 's throughout the code.

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.