Home > Back-end >  Why do I need to create a struct and then a pointer to it's address?
Why do I need to create a struct and then a pointer to it's address?

Time:12-18

I'm working with comedilib in a C program and I'm trying to understand this line:

comedi_cmd c, *cmd = &c;

comedi_cmd is a struct which contains a bunch of integers and a pointer to a data array. The variable c is not used anywhere else. If I omit creating c and just do:

comedi_cmd *cmd;

...then I start getting segfaults.

Why can we not simply create the pointer to a comedi_cmd struct? Is this a way of allocating memory?

Is this some C magic that I'm unaware of?

For more context, the line in question from the comedilib examples is here: https://github.com/Linux-Comedi/comedilib/blob/master/demo/tut3.c#L68

CodePudding user response:

It is evident that you need to create an object of the structure type that contains "a bunch of integers and a pointer to a data array".

This object will be changed in some functions. To change exactly the object and not a copy of the object within functions you need to pass it to functions by reference.

In C passing by reference means passing an object indirectly through a pointer to it. Dereferencing the pointer functions will have a direct access to the passed object.

You could write for example calling a function

some_function( &c );

However you can introduce an intermediate variable of a pointer type like

comedi_cmd *cmd = &c;

and use it in function calls instead of the expression &c.

some_function( cmd );

CodePudding user response:

Let's split the line into two lines:

comedi_cmd c;
comedi_cmd *cmd = &c;

The first line has the effect of allocating enough memory on the stack to contain variable c of type comedi_cmd. That's where your bunch of integers and a pointer will be stored in memory.

The second line defines cmd, a pointer to comedi_cmd, and initializes it with the address of c, which is where the the bunch of integers and a pointer are stored in memory.

If you were to define cmd uninitialized:

comedi_cmd *cmd;

then it would have an undefined value (address). Dereferencing it would likely cause a SIGSEGV, as you observed. You must make sure that cmd points to valid memory, and c is the valid memory in this case.

  • Related