[英]Assignment from incompatible pointer type[Wincompatible-pointer-types]
[英]warning: return from incompatible pointer type [-Wincompatible-pointer-types]|
我正在嘗試從 function 指針返回一個數組,代碼工作但在 C 中顯示“指針類型不兼容”的警告。 我想返回一個數組,它已經是動態分配的。 有人可以告訴我問題和解決方案嗎
#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;
}
有人可以給我這個警告的解決方案嗎?
unsigned short *
但您為int
分配空間並嘗試返回int*
。 我假設您想將unsigned short
存儲在分配的 memory 中。free
分配的 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
}
}
嘗試
#include <stdio.h>
#include <stdlib.h>
unsigned short *reverse_seq(unsigned short num) {
if (num == 0) return NULL;
int size = num + 1;
unsigned short *numbers = malloc((size_t) size * sizeof(unsigned short)); // THIS IS THE IMPORTANT CHANGE
for (int i = 0; i < num; i++) {
numbers[i] = (unsigned short) (num - i);
}
for (int i = 0; i < num; i++) {
printf("%d ", numbers[i]);
}
return numbers;
}
int main(void) {
int num = 5;
unsigned short *res = reverse_seq((unsigned short) num);
free(res);
return 0;
}
這將解決原始警告的主要問題。
重要的是分配您返回的正確類型的 memory。 問題是當請求指向unsigned short*
的指針時,您正在返回一個int*
。 不這樣做會對稍后訪問 memory 產生影響,因為從返回的指針訪問的 memory 布局與您分配 memory 序列的方式不匹配。
如果你想返回一個unsigned short
數組,你應該分配一個unsigned short
數組,而不是int
s:
unsigned short* reverse_seq(unsigned short num)
{
if (num == 0)
return NULL;
unsigned short* numbers = malloc(num * sizeof(unsigned short));
if (numbers) {
for (unsigned short i = 0; i < num; i++) {
numbers[i] = num - i;
}
}
return numbers;
}
您正在分配一個整數數組,但您正在返回一個短褲數組(通常是整數大小的一半)。 只需返回一個指向int
的指針,如下所示:
int *reverse_seq(unsigned short num) {
/* ... */
或分配一個短褲數組,如:
unsigned short *numbers = malloc(num * sizeof *numbers); /* and please, ***never*** cast the result of malloc() */
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.