P.Carlino P.Carlino - 1 month ago 12
C Question

Pointer in function change the address but outside it point 0x0

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.

Answer

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.