-1

Problem:

My program is running, but not successfully. It returns segmentation fault. Where might be the fault or how can I solve this problem?

Code:

#include<stdio.h>
#include<stdlib.h>
int main ()
{
  int *arr, i, j, n;
  printf ("Input the Size");
  scanf ("%d", n);
  arr=(int*)malloc(n*sizeof(int));
  for (i = 0; i < n, i++;)
  {
    *(arr + i) = i;
  }
  for (i = 0; i < n, i++;)
  {
    printf ("%d\n", *(arr + i));
  }
return 0;
}
Emma
  • 27,428
  • 11
  • 44
  • 69

1 Answers1

1

Change this:

scanf ("%d", n);

to this:

scanf ("%d", &n);

since scanf( const char * format, ...) expects a pointer as its parameter.


Moreover change this:

for (i = 0; i < n, i++;)

to this:

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

since the usual for loop syntax is:

for ( init; condition; increment )

Same for the second for loop: for (i = 0; i < n, i++;), which should be for (i = 0; i < n; i++)


You could allow your compiler to warn you about this, by passing compilation-enabling flags, like Wall for GCC (Compile like this: gcc prog.c -Wall). Then you would receive warnings like these:

prog.c: In function 'main':
prog.c:7:12: warning: format '%d' expects argument of type 'int *', but argument 2 has type 'int' [-Wformat=]
    7 |   scanf ("%d", n);
      |           ~^   ~
      |            |   |
      |            |   int
      |            int *
prog.c:9:20: warning: left-hand operand of comma expression has no effect [-Wunused-value]
    9 |   for (i = 0; i < n, i++;)
      |                    ^
prog.c:13:20: warning: left-hand operand of comma expression has no effect [-Wunused-value]
   13 |   for (i = 0; i < n, i++;)
      |                    ^
prog.c:5:16: warning: unused variable 'j' [-Wunused-variable]
    5 |   int *arr, i, j, n;
      |                ^
prog.c:7:3: warning: 'n' is used uninitialized in this function [-Wuninitialized]
    7 |   scanf ("%d", n);
      |   ^~~~~~~~~~~~~~~
gsamaras
  • 71,951
  • 46
  • 188
  • 305