简体   繁体   中英

C Pointers, understanding how to pass arrays to function

I'm currently revising on C pointers for an upcoming test and I came across a rather interesting program as I was running through the lecture slides.

#include <stdio.h>
#include <ctype.h>

void convertToUppercase(char *sPtr);//function prototype, input is a dereferenced pointer

int main(void)
{
    char string[] = "cHaRaCters and $32.98";

    printf("The string before conversion is %s\n", string);
    convertToUppercase(string); //Why can I just input the string array into the function? I don't need a pointer?
    printf("The string after conversion is %s", string);
}

void convertToUppercase(char *sPtr)
{
    while (*sPtr != '\0')//Clearly see the NULL terminating character, means the entire array is passed to the function.
    {
        *sPtr = toupper(*sPtr);
        sPtr++;
    }
}

What I don't understand is this particular line: convertToUppercase( string );

The function prototype requires a (char *sPtr) as an input, but for this case, the string array is just passed into the function call. How?

I don't really understand how this works. Can anyone help me to understand this code better?

My guess is that the array name itself 'string' already contain the address of the entire array itself (That's why when we assign pointers to array we don't put the '&')

Thank you in advance, take care!

Function parameters having array types are adjusted by the compiler to pointer types to the array element types.

So for example these two function declarations

void convertToUppercase(char sPtr[]);

and

void convertToUppercase(char *sPtr);

declare the same one function.

You may include the both declarations in your program though the compiler can issue a message that there are redundant declarations of the same function.

On the other hand, array designators used in expressions with rare exceptions (as for example using in the sizeof operator) are converted to pointers to their first elements.

So this function call

convertToUppercase(string)

is equivalent to the following function call

convertToUppercase( &string[0] )

Pay attention to that it will be better to declare and define the function the following way

char * convertToUppercase( char s[] )
{
    for ( char *p = s; *p; ++p )
    {
        *p = toupper( ( unsigned char )*p );
    }

    return s;
}

Arrays auto-convert to pointers when passed to functions. It just does, as if you a had written convertToUppercase((char*)string); . Just one more implicit type conversion rule.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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