Thread: not sure what the prob is

  1. #1
    Registered User
    Join Date
    Nov 2004
    Posts
    10

    not sure what the prob is

    Hello

    i wont write the code as it is too big i will just explain lol

    so i define a struct, create a pointer (will call him e) of that struct type, do a malloc with size of 1 struct (just for him to have a address), then i send the pointer in a function.

    In the function i realloc e (as now i know what size it as to be) create variables, i copy those variables into e. Inside the function e have all the camps ok. when i leave the function, its all messed up.

    What is the problem? does he free the space i realloced in the function when i leave it? since the variables are freed and i entered with a pointer, e then points into free memory instead of the variables?

    Well i cant figure it out :S nor how to conturn this lol

    Any help?
    i hope i wasnt too vague

    thanks

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    If you have a pointer outside a function, and you pass it to a function, that function can only change the value of what is already being pointed at.

    If you have a pointer outside a function, and inside the function you want to make it point to something else, then you instead need to pass a pointer to that pointer so you can make that pointer point to something else.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    void foo( char **bar )
    {
        *bar = malloc( strlen("World!" ) + 1 );
        strcpy( *bar, "World!" );
    }
    
    int main( void )
    {
        char array[] = "Hello ";
        char *s;
    
        s = array; /* point at the array */
        printf("%s", s );
    
        foo( &s ); /* s will now point to newly allocated memory */
    
        printf("%s", s );
        free( s );
    
        return 0;
    }
    Is that basicly what you're trying to do?

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Nov 2004
    Posts
    10
    Yes, with your explanation now the values are not lost when the function ends

    Thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Deal or No Deal listbox prob
    By kryptkat in forum Windows Programming
    Replies: 5
    Last Post: 03-30-2009, 06:53 PM
  2. wierd fopen prob
    By winterflood_j in forum C Programming
    Replies: 10
    Last Post: 02-24-2004, 06:31 AM
  3. prob function call
    By mouse163 in forum C++ Programming
    Replies: 4
    Last Post: 12-18-2002, 12:16 PM
  4. if-else prob..very basic so sorry to trouble u guys
    By bugeye in forum C Programming
    Replies: 2
    Last Post: 01-26-2002, 08:55 AM
  5. prob with fopen
    By ukcpaul in forum C Programming
    Replies: 2
    Last Post: 01-09-2002, 08:23 AM