art vanderlay art vanderlay - 7 months ago 39
C Question

new to C and struggling with use of *, & to reference objects

I am very new to C coming from deep PHP & BASH where variable variables make life easy. I am trying to understand in C how to create an object in

then call a
that works on this object, then on return to
merge this object back into the program.

I can get the scripts to compile, but it throws a
segmentation fault
on the

After reading lots of posts and tutorials I think I am mixing up when to use

scriptOne.c -> main()

int main(){
GstElement *myPipeline;
GstElement *myBin;
gst_bin_add (GST_BIN (myPipeline), myBin); // Segmentation Fault , main merge

scriptOne.c -> doAddBin()

void doAddBin(GstElement *MyBinAlpha){
char *bin_name;
MyBinAlpha = gst_bin_new (bin_name); <--This is where object is produced


ScriptTwo.c -> doWorkOnBin()

void doAddBin(GstElement *MyBinBeta){
src1 = gst_element_factory_make ("filesrc", "idFileSrc");
gst_bin_add (MyBinBeta,src1);
return; // work now finished, return to main()
// where myBin now contains src1

So I take I am not using the
correctly and need to replace it with
somewhere to stop the
segmentation fault

thanks Art


In C, all function parameters are pass by value. So changing the value of a function parameter is not visible outside of the function.

What you can do however is pass the address of a variable using the & operator, then inside the function you dereference that pointer using the * operator so that you're actually changing a variable in the calling function.

// accept the address of a pointer
void doAddBin(GstElement **MyBinAlpha){
    char *bin_name;
    // derefernce the pointer to assign to myBin in main
    *MyBinAlpha = gst_bin_new (bin_name); <--This is where object is produced


    ScriptTwo.c -> doWorkOnBin();

int main(){
    GstElement *myPipeline;
    GstElement *myBin;
    // pass in the address of the pointer
    // now myBin has been updated     
    gst_bin_add (GST_BIN (pipeline), myBin);
    return 0;