简体   繁体   中英

Allocating and deallocating memory, writing 100 numbers into an array, qsort to sort them in C

I'm attempting to allocate space for 100 doubles, check if the allocation was successful, and then deallocate the space. After that I'd like to use the original allocated space to write 100 random numbers to it and then sort them using qsort .

Here's the code I have to far

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

int main()
{
    double *num = (double*) malloc(sizeof(double) * 100);

    printf("%lf", *num);

    realloc(num, 0);

    return 0;
}

When I attempt to print *num , it gives me 0.00000 which seems wrong. I get the warning

 warning: ignoring return value of function declared with
 'warn_unused_result' attribute [Wunused-result] realloc(num, 0);

when compiling the program. I'm still unsure on how to make this work with an array.

I think you are trying to do this:

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

int main()
{
    double *num = (double*) malloc(sizeof(double) * 100);

    if (num) {
        printf("SUCCESS!\n");

        for (int i = 0; i < 100; i++) {
            num[i] = rand();
        }

        /* sort here */

        free(num);
    } else {
        printf("FAILURE!\n");
    }

    return 0;
}

It is bad practice to pass the value zero to the malloc family of functions. What happens then is implementation-defined, meaning that different compilers might give different results.

C17 7.22.3

If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.

This isn't normal use of realloc - normally the compiler expects you to use the return value. Hence the warning.

Forget about realloc(num, 0); and use free() instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM