Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

warning: return from incompatible pointer type [-Wincompatible-pointer-types]|

I am trying to return an array from the function pointer, the code work but shows a warning in C that "incompatible pointer type". I want to return an array and it is already dynamic allocated. Can somebody tell me the problem and the solution to it

#include <stdlib.h>
#include<stdio.h>
unsigned short *reverse_seq(unsigned short num)
{
    if(num==0) return NULL;
    int size=num+1;
    int* numbers=(int *) malloc(size*sizeof(int));
    for(int i=0;i<num;i++){
        numbers[i]=num-i;
    }
    for(int i=0;i<num;i++){
        printf("%d ",numbers[i]);
    }
    return numbers;
}
int main(void)
{
    int num=5;
    reverse_seq(num);
    return 0;
}

Can somebody give me the solution to this warning?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  • Your function is declared to return unsigned short * but you allocate space for ints and try to return an int*. I assume you want to store unsigned shorts in the allocated memory.
  • When you return a pointer to dynamically allocated memory, you should always assign that pointer to a variable so that you can free the allocated memory.
#include <stdio.h>
#include <stdlib.h>

unsigned short *reverse_seq(unsigned short num) {
    if (num == 0) return NULL;

    // corrected allocation (there's no need for num + 1 elements either):
    unsigned short *numbers = malloc(num * sizeof *numbers);

    if(numbers) {                       // check that allocation worked
        for (int i = 0; i < num; i++) {
            numbers[i] = num - i;
        }
    }

    // printing moved to `main` to make use of the data there

    return numbers;
}

int main(void) {
    unsigned short num = 5; // same type as `reverse_seq` wants
    
    unsigned short *numbers = reverse_seq(num);
    if(numbers) {                        // again, check that allocation worked
        for (int i = 0; i < num; i++) {
            printf("%d ", numbers[i]);
        }
        
        free(numbers);                   // free the memory
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading