2
void sort(struct node **s2) {
    struct node *x, *y;
    x = *s2;
    char *str;
    while (x != NULL) {
        y = x->n;
        while (y != NULL) {
            if (strcmp(x->name, y->name) > 0) {
                strcpy(str, x->name);
                strcpy(x->name, y->name);
                strcpy(y->name, str);
            }
            y = y->n;
        }
        x = x->n;
    }
}

This is showing a run time error. I don't know whats wrong I believe the sorting is correct It's selection sort The structure of my node is:

struct node {
    char *name;
    struct node *n;
};

It's showing runtime error.

3
  • Your sort function does not compile, you're missing a } Commented Aug 17, 2016 at 15:17
  • oh i m sorry i missed out a } here...i have all the } in my original program Commented Aug 17, 2016 at 15:20
  • Your algorithm is an unstable variant of selection sort. Its time-complexity is O(N^2). Try and implement merge sort, a much more efficient algorithm with worst-case time-complexity of O(N.log(N)). Commented Aug 17, 2016 at 15:33

2 Answers 2

5

char *str; ... strcpy(str,x->name); copies data pointed to by name to an someplace (it is undefined behavior) as str is an uninitialized pointer.

Just swap pointers.

       if (strcmp(x->name,y->name) > 0) {
         char *temp = x->name;
         x->name = y->name;
         y->name = temp;
       }
Sign up to request clarification or add additional context in comments.

3 Comments

thanks ,swapping the pointers works but I'm confused-what is wrong with swapping the data?.
Three reasons: any string might not have the space to store a longer string; and you have not allocated any memory to your scratch space *str; and execution time.
got it.Thank's a lot
1

char *str; This statement only create a pointer. There is no memory is associated with that;

strcpy(char* dest, char* src) simply copies the the content in the memory pointed by src to memory point by dest

In your case str not pointing to any memory location;

strcpy(str, x->name)

since str pointing to nothing, this statement endup with an error because strcpy fails to copy to str

instead of char* str; use char str[SIZE_MAX];

1 Comment

I'm afraid char str[SIZE_MAX]; is not an option because SIZE_MAX, the maximum value of type size_t, is much too large, likely larger than available memory and definitely too much for an automatic variable.

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.