help with simple functions

Discussion in 'C' started by buzz271, Sep 6, 2010.

  1. buzz271

    buzz271 New Member

    Joined:
    Sep 6, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Does anyone see anything wrong with these simple functions?

    Basically, the "get_field" gets a word from the file of unknown length and "add_char" will add the character to the string.

    The problem lies somewhere in the "add_char" function because the memory is never realloc'd. I don't get any error messages--the word is just blank when printed. :-(

    Code:
    char *add_char(char *string,char character)
    {
        char *tmp=realloc(string,sizeof(string)+sizeof(char));
        if(tmp!=NULL)
        {
            string=tmp;
        }
        string[sizeof(string)/sizeof(char)]=character;
        return string;
    }
    
    char *get_field(FILE *inputfile)
    {
        char character;
        char *field;
        
        field=(char*)malloc(sizeof(char)*2);
        
        do
        {
            character=getc(inputfile);
            field=add_char(field,character);
        }
        while(character!='\0');
        
        field[sizeof(field)]='\0';
        
        return field;
    }
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice