简体   繁体   English

为什么我需要返回函数的指针

[英]Why do I need to return the pointer of a function

I haven't programmed with pointers for a long time and I do not remember when I need to return a char * or not!我很久没有用指针编程了,我不记得我什么时候需要返回一个char * Let me make a example:让我举个例子:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/wait.h> 

void AllocMemory(char** buf);

int main(){
    
   char *array;

   AllocMemory(&array);

   printf("%s", array); //Printing and I dont make return
   
   free(array);

   return 0; 
}
    
void AllocMemory(char** buf){
    
    int bufSize = 10;
    int stringSize;
        
    *buf = calloc(bufSize, sizeof(char)); 
        
    if(*buf == NULL){
        printf("[ERROR] can't malloc %d bytes\n", bufSize);
        exit(1);
    }
    char *readpos = *buf; //point to a pointer of your array!
        
    while(1){   //looping until the alocated memory is enough to the inserted command

        do{

            fgets(readpos, bufSize, stdin); //reads a line from the specified stream

            stringSize = strlen(*buf); //getting the size of the array

            if (stringSize == 1)
            {
                printf("\nYou just pressed enter, pls type again: "); //checking if user just pressed enter
            }

        }while (stringSize == 1); //looping until user press only enter

    
        if (readpos[strlen(readpos)-1] == '\n'){ //Search from the end as there's where the newline should be if exists, the string fits on array and doesnt need to allocate more memory
                readpos[strlen(readpos)-1] = '\0';     //Remove \n from the string
                break;
        }   

        
        *buf = realloc(*buf, bufSize + stringSize * sizeof(char)); // Need to allocate more memory, because the before if its false
        if(*buf == NULL){
            printf("[ERROR] can't realloc more %d bytes\n", bufSize+stringSize);
            exit(1);
        } 

        readpos = *buf + stringSize; // Set the pointer to next position to read into 
    }
        
}

So in this case I think I don't need to return a char* , but sometimes I need to return it, I and I am wondering if its when its when the parameter is send as example:所以在这种情况下,我认为我不需要返回char* ,但有时我需要返回它,我和我想知道它何时发送参数作为示例:

char *examplefunc(char *buf){
   //Code here
}

So my question can be bad, but what I need to know, is when I need to return the char * or not!所以我的问题可能很糟糕,但我需要知道的是,我何时需要返回char *或不返回!

void redirection(char** stringSplited, char** cRedirection, char** fRedirection){ 

   //I has splited the `stringSplited` here and save some parameters do `cRedirection and to fRedirection`and I do not need any return;
}

It's always possible to change return value to output parameters.始终可以将返回值更改为输出参数。 For instance, here are two functions that both add two numbers.例如,这里有两个函数都将两个数字相加。

int add1(int a, int b) {
    return a+b;
}

void add2(int a, int b, int *output) {
    *output = a+b;
}

And then you invoke them just a little bit differently.然后你以稍微不同的方式调用它们。 But they work the same way.但它们的工作方式相同。

int x, y;
x = add1(5, 6);
add2(5, 6, &y);

This is not different just because it's a pointer.这并没有因为它是一个指针而不同。 A pointer is just a variable containing a memory address.指针只是一个包含内存地址的变量。 The function realloc has this signature:函数realloc具有以下签名:

void *realloc(void *ptr, size_t size)

But that's just a design choice.但这只是一种设计选择。 This would work just as good:这将同样有效:

void realloc(void *ptr, size_t size, void **output)

Or to put it in more general terms, this function:或者更笼统地说,这个函数:

T foo(<params>) {
    ...
    return <expr>;
}

can be converted to this:可以转换成这样:

void foo(<params>, T *output) {
    ...
    *output = <expr>;
}

The easiest way is to just write it as a wrapper:最简单的方法是将其编写为包装器:

void new_foo(<params>, T *output) {
    *output = old_foo(<params>);
}

Or vice versa:或相反亦然:

T *new_foo(<params>) {
    T *ret;
    old_foo(<params>, ret);
    return ret;
}

My confusion was why I need to return a char* if I can declare it in function like this void examplefucn(char ** buf);我的困惑是为什么我需要返回一个 char* 如果我可以在像这样的函数中声明它void examplefucn(char ** buf);

You don't have to.你不必。

Pointers are just a reference (address) pointing to some memory.指针只是指向某个内存的引用(地址)。 If you pass char* to a function, then the function will be able to use it to change the content stored at this address ;如果将char*传递给函数,则该函数将能够使用它来更改存储在该地址的内容; and naturally, the address you pass hasn't changed, so you may use the pointer you provided even outside of that function.自然地,您传递的地址并没有改变,因此您甚至可以在该函数之外使用您提供的指针。

You want to pass a char** when you want to modify a pointer itself and not the content it points to.当你想修改指针本身而不是它指向的内容时,你想传递一个char** In your example, you provide a char** to your AllocMemory() function, and it allocates memory at the address (which would be of type char* ) pointed to by your double pointer buf .在您的示例中,您为AllocMemory()函数提供了一个char** ,它会在您的双指针buf的地址(类型为char* )分配内存。 Returning anything is unnecessary, as you've modified the memory adequately, and so array in your main() will point to an address that has been initiated in your function.返回任何内容都是不必要的,因为您已经充分修改了内存,因此main() array将指向已在您的函数中启动的地址。 This address will point to the memory you initiated and manipulated in your function.该地址将指向您在函数中启动和操作的内存。

You're confused over whether or not to return values because you don't seem to fully grasp how pointers work - understandably so, it's an unintuitive idea.您对是否返回值感到困惑,因为您似乎没有完全掌握指针的工作原理 - 可以理解,这是一个不直观的想法。 But if you understand what you are accessing and the difference between a pointer char* and a pointer to a pointer char** , then you'll know when you want to return a pointer and when it's unnecessary.但是,如果您了解正在访问的内容以及指针char*和指向指针char**的指针之间的区别,那么您就会知道何时需要返回指针以及何时不需要返回。 It depends on the context, and it's unnecessary in this case.这取决于上下文,在这种情况下是不必要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM