Passing string to a function in C - with or without pointers?

前端 未结 3 1115
借酒劲吻你
借酒劲吻你 2020-12-13 05:11

When I\'m passing a string to the function sometimes I use

char *functionname(char *string name[256])

and sometimes I use it without pointe

相关标签:
3条回答
  • 2020-12-13 05:29

    An array is a pointer. It points to the start of a sequence of "objects".

    If we do this: ìnt arr[10];, then arr is a pointer to a memory location, from which ten integers follow. They are uninitialised, but the memory is allocated. It is exactly the same as doing int *arr = new int[10];.

    0 讨论(0)
  • 2020-12-13 05:33

    Assuming that you meant to write

    char *functionname(char *string[256])
    

    Here you are declaring a function that takes an array of 256 pointers to char as argument and returns a pointer to char. Here, on the other hand,

    char functionname(char string[256])
    

    You are declaring a function that takes an array of 256 chars as argument and returns a char.

    In other words the first function takes an array of strings and returns a string, while the second takes a string and returns a character.

    0 讨论(0)
  • 2020-12-13 05:48

    The accepted convention of passing C-strings to functions is to use a pointer:

    void function(char* name)
    

    When the function modifies the string you should also pass in the length:

    void function(char* name, size_t name_length)
    

    Your first example:

    char *functionname(char *string name[256])
    

    passes an array of pointers to strings which is not what you need at all.

    Your second example:

    char functionname(char string[256])
    

    passes an array of chars. The size of the array here doesn't matter and the parameter will decay to a pointer anyway, so this is equivalent to:

    char functionname(char *string)
    

    See also this question for more details on array arguments in C.

    0 讨论(0)
提交回复
热议问题