[英]Incompatible pointer type when I want to refer to a struct variable
I'm trying to iterate through a variables of a struct, with a function.我正在尝试使用 function 遍历结构的变量。 When I give the starting address of the pointer, I get a warning: "initialization from incompatible pointer type [-Wincompatible-pointer-types]".
当我给出指针的起始地址时,我收到一条警告:“从不兼容的指针类型 [-Wincompatible-pointer-types] 初始化”。 When I add this pointer to the function, I got an other warning: "passing argument 1 of 'ManipulateMessage' from incompatible pointer type [-Wincompatible-pointer-types]".
当我将此指针添加到 function 时,我收到另一个警告:“从不兼容的指针类型 [-Wincompatible-pointer-types] 传递 'ManipulateMessage' 的参数 1”。 I've searched these errors, but the results didn't help me.
我已经搜索了这些错误,但结果对我没有帮助。 The code actually is working, but I want to avoid undefined behavior.
代码实际上是有效的,但我想避免未定义的行为。 What is the cleanest way of this simple code?
这个简单代码最干净的方法是什么?
#include <stdio.h>
#include <stdlib.h>
/*************************************************
include
**************************************************/
//A message structure
typedef struct SIGNAL_STRUCTURE
{
int name;
int manipstarttime;
} signal_structure;
//Structure what collects all the signals
typedef struct SIGNAL_COLLECTOR
{
signal_structure EngSpeed;
signal_structure TransReqGear;
signal_structure CurrentGear;
} signal_collector;
//Function to do with the above structure
void ManipulateMessage(signal_structure * signal)
{
signal->name = 10;
signal->manipstarttime = 11;
}
/*************************************************
main
**************************************************/
void fcn(signal_collector * param_signal, int len)
{
int *pointer = param_signal;
while(len--)
{
printf("pointer: %p\n", pointer);
ManipulateMessage(pointer);
pointer += (sizeof(signal_structure) / sizeof(int));
}
}
int main(void)
{
signal_collector dummy;
fcn(&dummy, 2);
return 0;
}
On fcn()
you get signal_collector * param_signal
, but on the second line you say int *pointer = param_signal;
在
fcn()
你得到signal_collector * param_signal
,但在第二行你说int *pointer = param_signal;
. . So you cast
signal_collector
to int
, and then you send pointer
which is of type int *
to ManipulateMessage()
, which expect signal_structure *
as an argument.因此,您将
signal_collector
为int
,然后将int *
类型的pointer
发送到ManipulateMessage()
,它期望signal_structure *
作为参数。
Do you see the problem?你看到问题了吗? In order to resolve this issue, change the second line in
fcn()
to:为了解决此问题,
fcn()
中的第二行更改为:
signal_collector *pointer = param_signal;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.