guys I wrote this,
there's no errors, no warnings...
but it keeps crashing on execution..
any ideas ?????

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

struct data { char * name ; 
              int grade ;
       };
int compare_ints(const void *a, const void *b);
int compare_strings(const void *x, const void *y);
struct data *ptr;
static struct data array[5] ;
struct data c;     //The scanf function receives just memory adress of the " variables ". Not struct definitions... 

int main(void) {

    int i=0 ;


    printf(" Please enter 5 student names and grades: ");

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

        printf("\n name %d :  ",i+1);
        scanf(" %s ",c.name);
        printf("\n grade %d : ",i+1);
        scanf(" %d ",&c.grade);

    }

    printf("\n Students sorted by grade: \n");
    qsort((void*)array ,5, sizeof( struct data ),compare_ints);
       for (i=0;i<5;i++) {
        printf("\n %s %6d ",array[i].name, array[i].grade);
    }

    printf("\n Students in alphabetical order: \n");
    qsort((void*)array ,5, sizeof( struct data ),compare_strings);
         for (i=0;i<5;i++) {
              printf("\n %s %6d ",array[i].name, array[i].grade);
    }

    return 0;
}


//function definitions :


int compare_ints(const void *a, const void *b)
{
if (*(int *)a < *(int *)b)
        return(-1);
if (*(int *)a > *(int *)b)
        return(1);
else
        return(0);
}

int compare_strings(const void *x, const void *y)
{
return(strcmp( ((struct data *)x)->name,((struct data *)y)->name ) );
}

Recommended Answers

All 3 Replies

The problem is the structure, there is no memory allocated for name, that is just a pointer. scanf() does not allocate the memory.

struct data { char name[40] ; 
              int grade ;
       };

The problem is the structure, there is no memory allocated for name, that is just a pointer. scanf() does not allocate the memory.

thnx, i did this.
but theres another problem too.
it doesnt take the grades,
from name1 , goes to name 2.
and leaves the grades behind :/ ?!

  1. remove the spaces in scanf() format specifier string -- should be "%s", not " %s "

  2. lines 24 and 26: use array[i].name to populate the array.

commented: Always accurate and to the point. :-) +13
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.