0

Arrays are passed by reference since they are pointers that point to index 0. If that is the case, why does this programmer define a pointer char *sPtr as a parameter of function convertToUppercase() if he could just use char string [] as a parameter and have the values in the function main changed. Do both ways perform the same task or are they substantially different? Thanks!

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

 void convertToUppercase(char *sPtr ); 

 int main( void )

 {
 char string[] = "characters and $32.98"; /* initialize char array */

 printf( "The string before conversion is: %s", string );
 convertToUppercase( string );
 printf( "\nThe string after conversion is: %s\n", string );
 return 0;
 } 

 /* convert string to uppercase letters */

 void convertToUppercase(char *sPtr)
       {
        while (*sPtr != '\0' ) { /* current character is not '\0' */

         if ( islower( *sPtr))
         { 
           *sPtr = toupper( *sPtr );/* convert to uppercase */
         } 

         ++sPtr;
        } /* end while */
   } /* end function convertToUppercase */
  • 4
    *"Arrays are passed by reference since they are pointers that point to index 0"* Not true on both counts. Arrays aren't passed by reference ("pass by reference" has a specific meaning: passing a reference to a *variable* into a function), nor are arrays pointers that point to index 0. Arrays *degrade* to pointers in some situations, but they are not pointers. – T.J. Crowder Dec 02 '15 at 06:45
  • 1
    C doesn't have pass by reference, it only have pass by value. Pass by reference can be *emulated* by using pointers, but that's not really what happens in the code you show. – Some programmer dude Dec 02 '15 at 06:48
  • Thanks for the correction! My Deitel C programming textbook says those things though, did I misunderstand it? And did you get the gist of my question, which is, why do I need a pointer in the first place? – Rodrigo Proença Dec 02 '15 at 06:49

1 Answers1

0

I think both perform the same task, and I prefer the second way:

void convertToUppercase(char sPtr[]); which is probably safer, as it prevents sPtr from pointing to some other place inside the function.

artm
  • 17,291
  • 6
  • 38
  • 54