Thread: Global acess to dynamic allocated data

  1. #1
    Registered User
    Join Date
    Oct 2007
    Posts
    12

    Lightbulb Global acess to dynamic allocated data

    Hello

    I'm trying write program in GTK/C. Inside one callback function (called on button click) I read data from file and allocate them dynamic.
    Code:
     extern    gfloat *X;
    
    void on_wczytaj_clicked  (GtkButton *klawisz, gpointer  user_data)
    {
    ...
    		X = g_new0 (gfloat, number_of_points);	
    ....
                    X[i]=num;
    ....
    }
    Now I need to have access to this X from another callback function.
    I thought if X is global I have access to data ... but not.

    Code:
    void other_call_function  (GtkButton *klawisz2, gpointer  user_data)
    {
    ...
    	     printf(" X=%d", X[i]);
    ....
    }

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    As stated, such a thing ought to work.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    float *X;
    
    void foo(float value)
    {
       X = malloc(10 * sizeof *X);
       X[4] = value;
    }
    
    void bar(void)
    {
       printf("%g\n", X[4]);
    }
    
    int main()
    {
       foo(123.45);
       bar();
       return 0;
    }
    
    /* my output
    123.45
    */
    If the problem is in the '...', we'd need to see it. Otherwise, I'd recommend using the correct format specifier in printf for a gfloat -- I can't imagine that %d is the right one.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    Oct 2007
    Posts
    12

    Stupid mistake

    Hi

    You are right. Mistake was in ....
    It takes some time to find it. Local variable cover global and there was no access.
    But now it works correct.

    Thanks a lot :-)

    Daniel

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. problem with data in allocated memory
    By supi in forum C Programming
    Replies: 3
    Last Post: 06-09-2008, 02:06 AM
  2. Reading a file with Courier New characters
    By Noam in forum C Programming
    Replies: 3
    Last Post: 07-07-2006, 09:29 AM
  3. How To Save Dynamic Data
    By GaPe in forum C Programming
    Replies: 1
    Last Post: 11-25-2003, 10:41 AM
  4. help with making a dynamic array sized global stuct
    By Josh Kasten in forum C++ Programming
    Replies: 3
    Last Post: 01-05-2003, 06:23 AM
  5. to much global data?
    By d00-asu in forum A Brief History of Cprogramming.com
    Replies: 14
    Last Post: 09-10-2001, 12:45 PM