0

this is my code I am using in Unix machine, using cc compiler:

#include<stdlib.h>

main()
{
int nr=0,nc=0;
printf("Enter number of coulmns:");
scanf("%d",&nc);
printf("Enter number of rows:");
scanf("%d",&nr);
int *x,temp;
printf("Enter the matrix:\n");
for(int i=0;i<nr;i++)
{
   for(int j=0;j<nc;j++)
   {
      scanf("%d",&temp);
      *(x+i*nc+j)=temp;
   }
}
for(int i=0;i<nr;i++)
{
   for(int j=0;j<nc;j++)
   {
      printf("%d  ",*(x+i*nc+j));
   }
   printf("\n");
}
}

It takes number of rows and number of coulmns properly. But, I am getting core as soon as I enter first integer input to the matrix. Can anybody tell me what is the problem?

4
Contributors
3
Replies
4
Views
9 Years
Discussion Span
Last Post by kenji
0

I'm not supprised that produces a core dump. line 10 declared a pointer that points to nowhere -- there is no memory allocated to it. If x is supposed to be an array then use malloc() to allocate memory for the array x = malloc(10 * sizeof(int)); will allocate an array of 10 integers.

0

x is not initialised to point at anything and you are dereferencing *(x+i*nc+j) in your loops.

Before your loops, you need to make x point at something valid, such as the first element of an array with nr*nc elements.

0

Check out the pointer*, it should point to another variable of the same type

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.