gpt4 book ai didi

c - 警告 : initialisation from incompatible pointer type

转载 作者:太空宇宙 更新时间:2023-11-04 02:14:06 25 4
gpt4 key购买 nike

大家好,自从我接触 C 以来已经有一段时间了,所以我真的很生疏。我写了一个小程序来使用两个动态数组创建一个矩阵。但是,我收到此警告,但我不明白为什么?我想我不太确定指针的指针。有人可以帮我指出我的问题出在哪里吗?谢谢。

sm.c: In function ‘main’:
sm.c:11:13: warning: initialisation from incompatible pointer type [enabled by default]
sm.c: In function ‘makeMatrix’:
sm.c:27:3: warning: return from incompatible pointer type [enabled by default]


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

typedef int (**intptr) ();
intptr makeMatrix(int n);

int main(int argc, char *argv[]) {

int n = 2;

int **A = makeMatrix(n);
if(A) {
printf("A\n");
}
else printf("ERROR");
}

intptr makeMatrix(int size) {
int **a = malloc(sizeof *a * size);
if (a)
{
for (int i = 0; i < size; i++)
{
a[i] = malloc(sizeof *a[i] * size);
}
}
return a;
}

最佳答案

你在这里遇到了一些问题:

typedef int (**intptr) (); 
intptr makeMatrix(int n);

...

int **A = makeMatrix(n);

intptr typedef 声明了一个指向函数的指针,该函数接受不确定数量的参数并返回一个intA 不是 int

你需要写:

int **makeMatrix(int n);


int **A = makeMatrix(n);

使用 typedef 在这里没有多大帮助。

typedef int **(*intptr)();

它声明了一个指向函数的指针,该函数返回一个指向 int 的指针。但是写

intptr makeMatrix(int n);

会声明 makeMatrix() 返回一个指向函数的指针,而不是 int **

关于c - 警告 : initialisation from incompatible pointer type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10082949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com