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?
>Solution :
- Your function is declared to return
unsigned short *but you allocate space forints and try to return anint*. I assume you want to storeunsigned 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
freethe 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
}
}