首页 > 解决方案 > 编译返回“警告:来自不兼容的指针类型的赋值”

问题描述

问题

嗨,我有这个函数来检查当前路径并返回带有路径的 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;
   }
}

标签: c

解决方案


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

也是&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;
   }
}

推荐阅读