c - 编译返回“警告:来自不兼容的指针类型的赋值”
问题描述
问题
嗨,我有这个函数来检查当前路径并返回带有路径的 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;
}
}
解决方案
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;
}
}
推荐阅读
- reactjs - 如何从 Reactjs 网站复制导航
- javascript - 猫鼬(建造者模式)链式方法如何在幕后工作
- kotlin - Kotlin 聚合连续列表元素
- python - 为什么当我用 K-means 进行 4 个聚类时,我只有一个 intertia 而不是 4 个?
- python - Pyinstaller:制作了一个 exe 但无法正常工作。如何修复这些错误
- javascript - 侧边菜单打开时如何触发功能 | 离子反应
- swift - Swift - 停止截断 UIButton titleLabel
- sql - 如何根据sql中的状态id获取数据计数
- oracle - 如何在 Oracle Advanced Queuing 中向外部队列用户授予 CLOB 权限?
- c++ - 运行此示例,输出始终为 1。似乎 C++ 多态性不起作用?