0

i have a file function.c and main.c. In function.c there is this function

int GetRow(int descriptor,char* src)
{
    char app[1];
    char* carattere= (char*)malloc(sizeof(char));
    int count=0;
    int capp=0;

    while((capp=read(descriptor,app,sizeof(char)))>0
        &&app[0]!=';')
    {
        if(app[0]!='\n')
        {
            carattere[count]=app[0];
            carattere=(char*)realloc(carattere,sizeof(char)*(++count +1));
        }
    }
    src=carattere;
    if(capp<0)
    {
        return -1;
    };
    #define DEBUG
    #ifdef DEBUG
    printf("The line Detected was %s %s\n",carattere,src);
    #endif

}

And it work becouse when i use printf to see if the src point to the new address the return the same thing. The problem born in main.c where i call GetRow

char* pointer;
int file=open("prova.conf",O_RDWR);
GetRow(file,pointer);
printf("%s",pointer);

Becouse when i use printf itprint null. Using gdb then the call to GetRow i understand that the pointer point 0x0, so please can anyone tell and explain my issue?? Thanks and excuse me for my english.

P.Carlino
  • 661
  • 5
  • 21
  • [Please see this discussion on why not to cast the return value of `malloc()` and family in `C`.](http://stackoverflow.com/q/605845/2173917). – Sourav Ghosh Oct 31 '16 at 14:52
  • 1
    This is asked a lot. Change signature to `int GetRow(int descriptor,char** src)`, pass a pointer to pointer, and change the rest of the code accordingly. – Sergey Kalinichenko Oct 31 '16 at 14:52
  • Changing the value of an input argument inside a function, does not take effect on the value of this argument outside the function. – barak manos Oct 31 '16 at 14:55
  • @dasblinkenlight please can you explain to me the reason? – P.Carlino Oct 31 '16 at 14:57

1 Answers1

2

You still passing the char * src by value. If you want to change the value of the pointer you need to pass a reference to it. use char **src and set *src = carattere;

Just because you're passing a pointer doesn't mean you're necessarily passing by reference. If you malloc memory for src in main and then pass the reference to that memory (as you have the char * src) you can change the value at that reference by *src = *carattere but that's probably not what you want either.

cleblanc
  • 3,678
  • 1
  • 13
  • 16