1
votes

I'm trying to iterate through a variables of a struct, with a function. When I give the starting address of the pointer, I get a warning: "initialization from incompatible pointer type [-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]". 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;
}
1
Why are you even trying to treat a signal_structure * as an int *? - Andrew Henle
Replace int *pointer with signal_structure *pointer and pointer += (sizeof(signal_structure) / sizeof(int)); with pointer++; - Kevin
fcn() expects the argument to be an array of signal_collector structures. You're passing a single signal_collector, but telling it that there are 2 of them in the len argument. - Barmar
Also, while (len--) will iterate 3 times, not 2 times. while (--len) will iterate 2 times. - Barmar
@AndrewHenle Something like that. But I would probably use size_t i instead... :) - Some programmer dude

1 Answers

1
votes

On fcn() you get signal_collector * param_signal, but on the second line you say 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.

Do you see the problem? In order to resolve this issue, change the second line in fcn() to:

signal_collector *pointer = param_signal;