art vanderlay art vanderlay - 3 days ago 6
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

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

I can get the scripts to compile, but it throws a
segmentation fault
on the
main()
merge.

After reading lots of posts and tutorials I think I am mixing up when to use
myVar
,
*myVar
,
&myVar


scriptOne.c -> main()

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


scriptOne.c -> doAddBin()

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

doWorkOnBin(MyBinAlpha);


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

Answer

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;
    bin_name="bin_0";
    // derefernce the pointer to assign to myBin in main
    *MyBinAlpha = gst_bin_new (bin_name); <--This is where object is produced

    doWorkOnBin(*MyBinAlpha);

    ScriptTwo.c -> doWorkOnBin();
}

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