函数中的指针改变地址但在它之外的点0x0 [重复]

时间:2021-10-29 08:57:46

This question already has an answer here:

这个问题在这里已有答案:

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

我有一个文件function.c和main.c.在function.c中有这个功能

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

它工作因为当我使用printf来查看src是否指向新地址返回相同的东西。问题出现在main.c中,我称之为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.

因为我使用printf itprint null。使用gdb然后调用GetRow我明白指针指向0x0,所以请任何人可以告诉和解释我的问题??谢谢,请原谅我的英语。

1 个解决方案

#1


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;

您仍然按值传递char * src。如果要更改指针的值,则需要传递对它的引用。使用char ** src并设置* 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.

仅仅因为你传递一个指针并不意味着你必须通过引用传递。如果你在main中为src malloc内存然后将引用传递给那个内存(因为你有char * src),你可以用* src = * carattere更改该引用的值,但这可能不是你想要的。

#1


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;

您仍然按值传递char * src。如果要更改指针的值,则需要传递对它的引用。使用char ** src并设置* 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.

仅仅因为你传递一个指针并不意味着你必须通过引用传递。如果你在main中为src malloc内存然后将引用传递给那个内存(因为你有char * src),你可以用* src = * carattere更改该引用的值,但这可能不是你想要的。