1

I wonder why when using a pointer to char I got a problem but when I use a char array, I got nothing and it works?

int main()
{
    char* s="hello world124";   //doesn't work;
    //char s[20]="hello world124"; // it does work
    int i=0;
    for(;i<strlen(s);i++)
    {
        while(!(s[i]>='a' && s[i]<='z') && !(s[i]>='A' && s[i]<='Z') && s[i]!='\0' && s[i]!=32)
        {
            for(int j=i;s[j]!='\0';j++)
                s[j]=s[j+1];
        }
    }
    s[i]='\0';
    printf("%s",s);

    return 0;
}
  • @pzaenger The compiler appends the terminating null - it's implied that any string literal is terminated in such manner. – Kuba hasn't forgotten Monica Jun 07 '20 at 16:33
  • The declaration `char* s="hello world124";` makes `s` a pointer to a **constant** string literal, as explained in the linked duplicate. But `char s[20]="hello world124";` declares a **modifiable** array and initializes it with the *data* from the literal. – Adrian Mole Jun 07 '20 at 16:37

1 Answers1

2

char* s="hello world124";

s is a pointer to the string literal. You cant modify the string literal in C. It is an Undefined Behaviour

char s[20]="hello world124"; is a char array which you can modify

char s[20]="hello world124";
char* p = s;

p is referencing char array. You can modify it.

char* s=(char []){"hello world124"}; - s is referencing char array - you can modify it

0___________
  • 60,014
  • 4
  • 34
  • 74