-1

I wrote and ran this code to practice the basic algorithm. but this program operation is stopped. What is the problem?

#include <stdio.h>
#include <stdlib.h>

int bans(const void *a, const void *b) {
    return (*(int *)a - *(int *)b);
}

int main() 
{ 
    int m, i;
    int* arr;
    scanf("%d", &m);
    arr = (int*)malloc(sizeof(int) * m);
    for (i = 0; i < m; i++) {
        scanf("%d", arr[i]);
    }
    int n = sizeof(arr)/sizeof(arr[0]);
    for (i = 0; i < n; i++) printf("%d ", arr[i]);
    qsort(arr, n, sizeof(arr[0]), bans);
    for (i = 0; i < n; i++) printf("%d ", arr[i]);
    free(arr);
    return 0;
}
  • `scanf("%d", arr[i]);` --> `scanf("%d", &arr[i]);` or `scanf("%d", arr + i);`, Use `m` instead of `n`. – BLUEPIXY Sep 27 '17 at 13:02
  • Please read [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) by Eric Lippert. – Filburt Sep 27 '17 at 13:04

2 Answers2

2
  1. scanf requires a pointer to arr[i]: arr + i would suffice.

  2. sizeof(arr) is actually sizeof(int*). Use m for the number of elements. The idiom you're using only works for array types, not pointer types.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

The primary problem is in the statement

  scanf("%d", arr[i]);

where arr[i] is of type int. You need to pass a pointer to type (int), like either

scanf("%d", &arr[i]);

or

scanf("%d", arr+i);

Enable compiler warning to the highest level, your compiler should warn you about the expected type mismatch.

After that, in this case,

  int n = sizeof(arr)/sizeof(arr[0]);

is erroneous, as sizeof(arr) is the same as sizeof (int *). You don't need a new variable, at all. Use m.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261