【问题标题】:Compilation returning "Warning: assignment from incompatible pointer type"编译返回“警告:来自不兼容的指针类型的赋值”
【发布时间】:2021-02-25 12:53:49
【问题描述】:

问题

嗨,我有这个函数来检查当前路径并返回带有路径的 char 指针。但是当我使用 GCC 进行编译时,它会返回这两个警告。我尝试了一些解决方案,但无法解决。

应该如何处理这个警告?

警告

In file included from C:\Users\Lsy\Documents\C\murtza_debug\main.c:10:0:
C:\Users\Lsy\Documents\C\murtza_debug\system/path.h:6:10: warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
 int *p = cwd;
          ^~~
C:\Users\Lsy\Documents\C\murtza_debug\system/path.h: In function 'get_path':
C:\Users\Lsy\Documents\C\murtza_debug\system/path.h:9:7: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
     p = &cwd;
       ^

代码

#include <unistd.h>
#include <stdio.h>
#include <limits.h>

char cwd[8024];
int *p = cwd;

int* get_path() {
    p = &cwd;
    if (getcwd(cwd, sizeof(cwd)) != NULL) {
        return p;
   }
}

【问题讨论】:

  • 您正在尝试将 char 指针分配给 int 指针。
  • 您将一个char 指针分配给一个int 指针,您为什么希望它能够工作?另外,p = &amp;cwd; 在任何情况下都是错误的,请删除&amp;
  • 所以是的,int * 类型与 char * 不兼容(在特定的 C 语言“兼容”意义上)。我不清楚你为什么首先将 p 声明为 int * 而不是 char *
  • 下一个问题:当if 不为真时,你的函数返回什么?
  • @mch 这只是一个测试功能

标签: c


【解决方案1】:

cwd 是一个char 的数组,它在被分配之前被转换为指向数组第一个元素的指针char*。因此,您应该使用char*,而不是int*,作为p 的类型,让它接受它并使用char* 作为get_path() 的返回类型,以返回p

另外&amp;cwd 是另一种类型的指针char(*)[8024](指向数组本身的指针)。应该是cwd 只使用一种类型的指针。

#include <unistd.h>
#include <stdio.h>
#include <limits.h>

char cwd[8024];
char *p = cwd;

char* get_path() {
    p = cwd;
    if (getcwd(cwd, sizeof(cwd)) != NULL) {
        return p;
   }
}

【讨论】:

  • 我确实更改了函数,现在 GCC 返回“警告:从不兼容的指针类型返回 [-Wincompatible-pointer-types] > return p;”
  • @BlackCoral 抱歉,get_path() 的返回类型也应该更改。
猜你喜欢
  • 1970-01-01
  • 2016-09-16
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 2013-06-21
  • 2011-06-21
  • 1970-01-01
  • 2013-05-26
相关资源
最近更新 更多