C pass a nested structure within a structure to a function? - c

I have a address to a nested struct problem that I haven't been able to solve for a while right now.
So I have a ModuleStruct that holds a sensorStruct.
No problem to pass the address to the ModuleStruct in main. But when I do want to pass the address to the inner struct "SensorStruct" so readVoltage function can store the values, It fails.
Been googling and checking StackOverflow without finding anything that works. I hope I just done something stupid so it's easy to get it going.
Will be super happy if anyone could point me in the right direction (*puufh ;) )
typedef struct
{
int32_t Voltage;
int32_t Current;
}SensorStruct;
typedef struct
{
SensorStruct SensorData;
}ModuleStruct;
int main(void)
{
ModuleStruct Module_Data;
Sensor_Collect(&Module_Data);
}
void Sensor_Collect(ModuleStruct *Module_Data)
{
/// Here is the problem, I do not know how to pass the address of the SensorStruct
ReadVoltage(Module_Data->SensorData);
}
void ReadVoltage(SensorStruct *Sensor_Data)
{
Sensor_Data->Voltage = 5;
Sensor_Data->Current = 3;
}

Code that works. Take note that Sensor_Collect function is defined after ReadVoltage function, so it knows it's type when it calls it. Always compile your code with all warnings turned on.
#include <stdio.h>
#include <stdint.h>
typedef struct {
int32_t Voltage;
int32_t Current;
} SensorStruct;
typedef struct {
SensorStruct SensorData;
} ModuleStruct;
void ReadVoltage(SensorStruct *Sensor_Data) {
Sensor_Data->Voltage = 5;
Sensor_Data->Current = 3;
}
void Sensor_Collect(ModuleStruct *Module_Data) {
ReadVoltage(&(Module_Data->SensorData));
}
int main(void) {
ModuleStruct Module_Data;
Sensor_Collect(&Module_Data);
printf("voltage: %d\n", Module_Data.SensorData.Voltage);
printf("current: %d\n", Module_Data.SensorData.Current);
return 0;
}

Related

Init a const var in a struct after the struct variable is created

I have a c struct that has a const variable.
typedef struct {
u32 status;
const u32 dir_search_idx;} FS_OBJ;
What I would like to do is init the const variable in a function once I have created the struct object. I guess I want to do something similar to what a constructor would do in c++. Is it possible to do something similar in c? Thanks
This should work perfectly fine if you are using C99 or newer and want to initialize the const variable when creating the struct:
FS_OBJ obj = { .status = /* something */, .dir_seach_idx = /* something */ };
You can't modify the const variable after creating the struct. Then you would have to remove the const keyword as mentioned by user3386109 in the comments.
I think const is not the right tool for what you are looking for. You can put data (structs) and behavior (functions) in a *.c file and provide public functions in the corresponding header file. This way you can mimic the equivalent c++ code that you want and hide the data and of course, you can define a constructor. A great book that might help is The GLib/GTK+ Development Platform. In chapter 3 you can find a good introduction to Semi-Object-Oriented Programming in C.
Here is a possible implementation, not necessarily the best one:
/src/main.c
#include <stdio.h>
#include "point.h"
int main()
{
Point *p1 = init(6, 7);
printf("%d\n", getX(p1));
printf("%d\n", getY(p1));
Point *p2 = init(12, 14);
printf("%d\n", getX(p2));
printf("%d\n", getY(p2));
setX(p2, 16);
printf("%d\n", getX(p2));
setY(p2, 16); /* error; we want y to initialize once and remain constant. Also accessing y with p2->y is an error too. */
printf("%d\n", getY(p2)); /* getY is ok */
freep(p1);
freep(p2);
}
/src/point.h
typedef struct _Point Point;
Point *init(int, int);
int getX(Point *);
void setX(Point *, int);
int getY(Point *);
void freep(Point *);
/src/point.c
#include <stdlib.h>
#include "point.h"
struct _Point{
int x;
int y;
};
Point *init(int x, int y)
{
Point *temp;
temp = malloc(sizeof(Point));
temp->x = x;
temp->y = y;
return temp;
}
int getX(Point *p)
{
return p->x;
}
void setX(Point *p, int x)
{
p->x = x;
}
int getY(Point *p)
{
return p->y;
}
void freep(Point *p)
{
free(p);
}
Furthermore, if we need a private method in our class, we do not provide a declaration of it in the header and also we use static to restrict its access within the class's file.

Adding a parameter block to a function

Yesterday I had a problem with a function, turned out I forgot to declare a variable of the structure type, it is clear now what was the problem. I've modified my code, and I got another error messages, however it looks like the code actually s working.
I googled the problem but I can't really fit the solutions to my code. Can somebody shows and explain me what would be the clean way of the below code?
#include <stdio.h>
/*************************************************
include
**************************************************/
//A signal structure
typedef struct SIGNAL_STRUCTURE
{
int id;
int time;
}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 ManipulateSignal(signal_structure * signal)
{
signal->id = 10;
signal->time = 11;
}
/*************************************************
main
**************************************************/
void fcn(signal_collector * param_signal, int len)
{
int *pointer = param_signal;
while(len--)
{
ManipulateSignal(pointer);
pointer += (sizeof(signal_structure) / sizeof(int));
}
}
int main(void)
{
signal_collector foo;
fcn(&foo, 1);
return 0;
}
You can't use a typedef name as a function argument. You need to declare a variable with that type, and pass the address of the variable.
int main(void) {
param_collector my_pc;
fcn(&my_pc);
return 0;
}
You can only pass the reference to the object, but you forgot to define this object.
int main(void)
{
param_collector param_collector;
fcn(&param_collector);
return 0;
}
but I would give rather call the variable a distinct name (not the same as type)

Can't pass typedef struct to function by reference

I'm trying to pass a custom type object to a function by reference, and I can't figure out what I could be doing wrong. I read How do you pass a typedef struct to a function? as well as other references and could swear I'm already doing exactly that. I cleared out everything else I'm doing and even this spartan code throws 5 errors. Help me, Stackexchange; You're my only hope!
The goal is simply to be able to alter the values in the array in the object.
#include <stdio.h>
#include <math.h>
typedef struct structure {
char byte[10];
char mod;
} complex;
void simpleInit (complex *a, char value) {//put the value in the first byte and zero the rest
a.byte[0] = value;
char i;
for (i = 1; i < 10; ++i) {
a.byte[i] = 0;
}
a.mod = 1;
}
void main () {
complex myNumber;
char value = 6;
simpleInit (myNumber, value);
}
When I attempt to run this I get this error and 4 similar:
test2.c:10:3: error: request for member ‘byte’ in something not a structure or union
a.byte[0] = value;
a is a pointer type, so you need to de-reference it to use it. Typically that's done with the arrow operator:
a->byte[i] = 0;
Since this is just an array of bytes you can also quickly "zero" it:
memset(a, 0, 10);
Though given how important 10 is in your code you should codify that in a constant or a #define.
When you pass a value by reference you need to use asterisk to access al fields of the structure, for example:
(*a).byte[0] = value;
Happily you have -> as a shortcut, so this will be:
a->byte[0] = value;
Also do not forget to call the & (address of) operator when you call simpleInit.
#include <stdio.h>
#include <math.h>
typedef struct structure
{
char byte[10];
char mod;
} complex;
void simpleInit (complex *a, char value)
{
char i;
a->byte[0] = value;
for (i = 1; i < 10; ++i) {
a->byte[i] = 0;
}
a->mod = 1;
}
int main()
{
complex myNumber;
char value = 6;
simpleInit (&myNumber, value);
}

Accessing a struct without the struct being global

I've got a struct called members which contains a bunch of char arrays and integers. The struct has been declared in Header.h and defined it by "struct members pt" in source.c, inside main. From here a for-loop is being runned 5 times and adding variables to the character arrays and ints in pt[x].
Now I need to be able to access this from a function called void search(int a); (Should probably not be a void since I want it to return a value. But I'll fix that later)
What void search is supposed to do is basicly
int willReturn[10];
int b = 0;
for(int x = 0; x<a; x++)
{
if(pt[x].hasPayed == 0)
{
willReturn[b] = x;
b++;
}
}
There might be something wrong about that code, but the thing that I need to know is how I can access pt[x].hasPayed.
Any ideas?
I do not want to use any global variables.
Thank you in advance.
Below sample code might help you.
header.h
struct members {
int hasPayed;
};
main.c
#include <stdio.h>
#include <string.h>
#include "main.h"
typedef struct members MEMBERS;
void print_member(MEMBERS *pt) {
int i;
for(i =0 ; i< 10; i++)
{
printf(" %d\n",pt[i].hasPayed);
}
}
void main () {
MEMBERS pt[10];
int i;
for(i =0 ; i< 10; i++)
{
pt[i].hasPayed= i;
}
print_member(pt);
}
Instead of print_member code your search logic.
Pass a pointer to pt as a paraamter to search. e.g void search(int a, struct members *pt).
Another way if you don't want to pass pointers. Place pt in a function as a static variable.
struct members** ____get_pt(){
static struct members pt[ /* size */ ];
/*
or for dynamical size,
static struct members* pt;
*/
return &pt;
}
// Define a macro for convenience, above where you want to use 'pt'.
#define PT (*____get_pt())
Then you can use PT[x].hasPayed everywhere, without global variables.
However, this could do not improve your code ...

How to change pass a struct to a function by reference in c

#include <stdio.h>
struct player{
int life;
};struct player info;
void name(struct player *info);
int main(void)
{
info.life = 20;
name(&info);
printf(">>>>%d", info.life);
return 0;
}
void name(struct player *info)
{
info.life = 20
}
Hi, well this is just a practice code I am trying to pass a struct to a function by reference, but how do I change the value of the int in the struct? when i try to compile
info.life = 20; I get an error, what am i doing wrong? I also tried doing
*info.life = 20; but I also got an error. Thanks you guys! :)
Here:
void name(struct player *info)
{
info.life = 20;
}
that should be info->life. because info is a pointer.
I usually typedef my structs to make it more readable.
typedef struct _Player
{
int life;
} Player;
Then to access your struct or pass it in you would do:
void name(Player *pInfo)
{
pInfo->life = 20;
}
I also prepend a p for any pointer variable, so that you can easily see when you have a pointer or not.

Resources