Question

I am trying to create functions instead of having bunch of code in main but I am not able to do that since I am doing something wrong with the functions, here is what my code looks like:

void static notebook(GtkWidget *table, GtkWidget *notebook) {
 notebook = gtk_notebook_new();
 ...
 attaching table to notebook
 ...
}


int main(int argc, char *argv[]) {
 GtkWidget *table;
 GtkWidget *notebook;

 ...
 notebook(table, notebook);
 ...
}

Could someone point out my problem and help me fix it please?

Was it helpful?

Solution

The problem seems to be that you are assuming that parameters are both for input and ouput of a function. But in C, function parameters are always copies. So when you do:

void static notebook(GtkWidget *table, GtkWidget *notebook) {
    notebook = gtk_notebook_new();

You are modifying the local copy of the notebook pointer, not the one from main. The notebook pointer in main remains uninitialized.

To do what you try, minimum changes, would be:

void static notebook(GtkWidget **table, GtkWidget **notebook) {
    *notebook = gtk_notebook_new();
    ...

int main() {
 GtkWidget *table;
 GtkWidget *notebook;

 ...
 notebook(&table, &notebook);

But doing that with every pointer is ugly and cumbersome. So I would recommend some refactoring:

  1. Functions that create a thing should return that thing.
  2. Functions that take a lot of related values should take a single value of type struct whatever.
  3. Remember that struct parameters in C are usually passed as pointers, so you get the in-out parameter for free!

Something like this:

struct Notebook
{
    GtkWidget *table;
    GtkWidget *notebook;
};

void static notebook(struct Notebook *notebook) {
     notebook->notebook = gtk_notebook_new();
     ...
}
int main(int argc, char *argv[]) {
 Notebook nb;

 ...
 notebook(&nb);
 ...
}

OTHER TIPS

take param "GtkWidget *table" for example, you only pass a pointer parameter to the function, and allocate memory to it : table = new xxx.

but GtkWidget *table here is a temp param only exist in function notebook, there are no way it can affect the real parameters in main. GtkWidget *table, GtkWidget *notebook's values stay unchanged after "notebook" function is finished.

so you can use pointer to pointer in notebook function's declaration, like this

 void static notebook(GtkWidget **table) {
     *table = new gtk_notebook_new();
 }

then in main, invoke like this:

int main(int argc, char *argv[]) {
 GtkWidget *table;

 notebook(&table);
 ...
}

that should do it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top