C语言中ctype.h函数的用法,请问这两个代码的区别是什么,第二个代码尝试将convertToUppercase函数写入main函数,写入后发生错误

C语言中ctype.h函数的用法,请问这两个代码的区别是什么,为什么第一个代码正常运行,第二个代码尝试将convertToUppercase函数写入main函数,写入后发生错误,无法运行。

第一个代码如下:

#include <stdio.h>
#include<ctype.h>
#include<string.h>
void convertToUppercase(char*sPtr);
int main() {
   char string[20]="happy birthday";
   convertToUppercase(string);
   printf("%s",string);
   return 0;
}
void convertToUppercase(char*sPtr){
   while(*sPtr!='\0'){
       if(islower(*sPtr))
         *sPtr=toupper(*sPtr);
       ++sPtr;
   }
}

正常运行,输出:HAPPY BIRTHDAY

第二个代码如下:

#include <stdio.h>
#include<ctype.h>
#include<string.h>
int main() {
   char string[20]="happy birthday";
   while(*string!='\0'){
       if(islower(*string))
         *string=toupper(*string);
       ++string;
   }
   printf("%s",string);
   return 0;
}

无法运行

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

int main()
{
    char string[20] = "happy birthday";
    char *ptr = string;  // 如果是函数,实际上传入的是指向数组开头的指针。
    while (*ptr != '\0')
    {
        if (islower(*ptr))
            *ptr = toupper(*ptr);
        ++ptr;
    }
    printf("%s", string);
    return 0;
}

第二个代码里,string是指针常量,修改如下,供参考:

#include <stdio.h>
#include<ctype.h>
#include<string.h>
int main() {
   int i = 0;   //修改
   char string[20]="happy birthday";
   while(*(string+i) != '\0'){  //修改
       if(islower(*(string+i))) //修改
         *(string+i)=toupper(*(string+i));//修改
       i++; //++string;修改
   }
   printf("%s",string);
   return 0;
}