Why char[] work,but char * doesn't

311 Views Asked by At

code1:

 int main()
    {
        char tmp[20] = "1.04";
        printf("float str is %s\n",tmp);
        delcharPoint(tmp);
        printf("%s\n",tmp); 
    }
    void delcharPoint(char *pStr)
    {
        char *pTmp = pStr;
        int flag_0 = 0;
        printf("*pTmp = %s\n",pTmp);
        printf("*pTmp = %s\n",pTmp);
        if(*pStr == '0')
        {
            pStr++;
            flag_0 = 1;
        }
        while(*pStr != '\0')
        {
            if(*pStr != '.')
            {
                *pTmp++ = *pStr;
                pStr++;
            }
            else
            {
                pStr++;
                if(flag_0 ==1 && *pStr == '0')
                {   
                    pStr++;
                }
            }
        }
        *pTmp = '\0';
    }

This code worked well and it print:

float str is 1.04
*pTmp = 1.04
*pTmp = 1.04
104

Code2:

int main()
        {
            char *tmp = "1.04";
            printf("float str is %s\n",tmp);
            delcharPoint(tmp);
            printf("%s\n",tmp); 
        }
        void delcharPoint(char *pStr)
        {
            char *pTmp = pStr;
            int flag_0 = 0;
            printf("*pTmp = %s\n",pTmp);
            printf("*pTmp = %s\n",pTmp);
            if(*pStr == '0')
            {
                pStr++;
                flag_0 = 1;
            }
            while(*pStr != '\0')
            {
                if(*pStr != '.')
                {
                    *pTmp++ = *pStr;
                    pStr++;
                }
                else
                {
                    pStr++;
                    if(flag_0 ==1 && *pStr == '0')
                    {   
                        pStr++;
                    }
                }
            }
            *pTmp = '\0';
        }

This code doesn't work,it print:

float str is 1.04
*pTmp = 1.04
*pTmp = 1.04
Segmentation fault

The difference between two codes only is I use char[] in code1 and char * in code2.I have searched the difference between char[] and char *.But I still don't what cause the difference between these code.

1

There are 1 best solutions below

0
On BEST ANSWER

Here:

char *tmp = "1.04";

"1.04" is a string literal and string literals are immutable, meaning that it cannot be changed. Attempting to do so results in Undefined Behavior.

On the other hand,

char tmp[20] = "1.04";

creates a char array, copies "1.04" into it. Modifying the contents of an array is legal.